下面是我正在尝试运行的修改代码。我基本上将SQL查询文件作为文本传递以从vba运行查询并使结果自动返回到工作表中。
当我连接到SQL Server时,这对我有用,但是当我使用Oracle服务器时,似乎记录集已关闭,因此我猜测我的连接字符串是个问题。但我真的不知道我的问题在哪里,因为我的连接字符串中的信息与 TNSNAMES 匹配,我知道我的用户名和pw处于正常工作状态,因为我可以登录并通过PL / SQL。
此外,当我在PL / SQL中运行时,我的查询运行正常,不,它不会返回NULL
集。我也尝试过一个非常简化的SELECT * FROM table WHERE ROWNUM <= 2
查询,它仍然不起作用。
Edit1:但是,Select 1 FROM dual
有效。
Edit2:所以在我运行Select 1 FROM dual
查询之后,真正简单的查询起作用了。但是,原始查询仍然无效。
Sub Con_DatabaseName(EvalDate As String, fPath1 As String, fName1 As String, fPath2 As String, fName2 As String)
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
con.ConnectionString = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=xxxx)" & _
"(CONNECT_DATA=(SERVICE_NAME=xxxx))); uid=xxxx; pwd=xxxx;"
con.CommandTimeout = 0
con.Open
Dim QueryFile As String
Dim SqlStatement As String
Dim hFile As Long
QueryFile = fPath2 & fName2
'Debug.Print QueryFile
hFile = FreeFile
Open QueryFile For Input As #hFile
SqlStatement = Input$(LOF(hFile), hFile)
Close #hFile
Debug.Print SqlStatement
Dim col As Integer
rs.Open SqlStatement, con
'Checks if my recordset is open.
If rs.State = 1 Then
MsgBox ("Recordset is open")
ElseIf rs.State <> 1 Then
MsgBox ("Recordset is not open")
Exit Sub
End If
rs.Close
con.Close
End Sub