【发布时间】:2015-03-14 05:47:14
【问题描述】:
所以我对 Visual Basic 相当陌生,而不是 SQL,但我在网上找到了一段我已经编辑过的代码,我让它像我需要将数据带入 Excel 工作表一样工作。问题是,当我更改参数以查找不同的记录集时,如果我让论坛查看表中的数据(例如:sheet2 公式查看 sheet1 A1),公式本身被删除并更改为“#REF!” .我试过美元符号,但没有用。我什至尝试在参数更改后注释掉清除表格的行。是否有我可以设置的查询表选项?或者是否有不同的方式来显示结果而不是查询表?
Visual Basic sn-p:
Sub ParameterQueryExample()
'---creates a ListObject-QueryTable on Sheet1 that uses the value in
' Cell A1 as the ProductID Parameter for an SQL Query
' Once created, the query will refresh upon changes to A1.
Dim sSQL As String
Dim qt As QueryTable
Dim rDest As Range
'--build connection string-must use ODBC to allow parameters
Const sConnect = "ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=Braden-PC;" & _
"Database=CI_APEXALPHA;"
'--build SQL statement
sSQL = "SELECT *" & _
" FROM apexalpha.CI_AAD_SAMPLE" & _
" WHERE SAMPLE_DESCRIPTION = ?;"
'--create ListObject and get QueryTable
Set rDest = Sheets("Sheet1").Range("A2")
'--rDest.CurrentRegion.Clear 'optional- delete existing table
Set qt = rDest.Parent.ListObjects.Add(SourceType:=xlSrcExternal, _
Source:=Array(sConnect), Destination:=rDest).QueryTable
'--add Parameter to QueryTable-use Cell Z1 as parameter
With qt.Parameters.Add("SAMPLE_DESCRIPTION", xlParamTypeVarChar)
.SetParam xlRange, Sheets("Sheet1").Range("A1")
.RefreshOnChange = True
End With
'--populate QueryTable
With qt
.CommandText = sSQL
.CommandType = xlCmdSql
.AdjustColumnWidth = True 'add any other table properties here
.BackgroundQuery = False
'-- .Refresh
End With
Set qt = Nothing
Set rDest = Nothing
End Sub
【问题讨论】: