vb代码如下:
Function GetDCF(vari As String)
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim strConn As String
Dim sql As String
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=xxxxxx;INITIAL CATALOG=xxxxx;INTEGRATED SECURITY=sspi;"
cn.Open strConn
sql = "select '" & vari & "' from TBLmontecarlodcf where COMPANY = '" & Range("A2").Value & "' "
rs.Open sql, cn, adOpenDynamic, adLockOptimistic
GetDCF = rs.Fields(vari)
cn.Close
Set rs = Nothing
Set cn = Nothing
End Function
但它不会在excel中返回值。相反,如果我用sql server中的真实字段替换'“& vari&”',并把GetDCF = rs!fieldname,我确实得到了值。请问GetDCF = rs.Fields(vari)在哪里出错?
答案 0 :(得分:0)
您似乎将您的字段用sql中的单引号括起来。假设传递给函数的vari
的值为Person
且Range("A2").value
为Catepillar
,那么您的sql将显示为select 'person' from TBLmontecarlodcf where COMPANY = 'Catepillar'
相反:
sql = "select " & vari & " from TBLmontecarlodcf where COMPANY = '" & Range("A2").Value & "' "