我目前正在尝试弄清如何从VBA运行.sql文件。我可以让VBA在其中运行sql代码,但是由于已经编写了SQL脚本,因此我希望能够调用文件,运行代码并将数据传递回Excel。即使正在调用文件并将代码传递回VBA来运行,也可以,但是在这里维护代码比在VBA编辑器中更容易。
数据库是Oracle,但是我已使连接运行并正在运行atm。
' Makes the SQL call to collect the data. Dim strConOracle As String Dim oConOracle, oRsOracle Dim strSQL As String Dim lngCount As Long Dim strCount As String strConOracle = "Driver={Microsoft ODBC for Oracle}; CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" strConOracle = strConOracle & "(HOST=" & HOST & ")(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=" & DBNAME strConOracle = strConOracle & "))); uid=" & ORACLE_USER_NAME & " ;pwd=" & ORACLE_PASSWORD & ";" Set oConOracle = CreateObject("ADODB.Connection") Set oRsOracle = CreateObject("ADODB.RecordSet") oConOracle.Open strConOracle strSQL = "" Set oRsOracle = oConOracle.Execute(strSQL) ActiveSheet.Cells.CopyFromRecordset oRsOracle oConOracle.Close Set oRsOracle = Nothing Set oConOracle = Nothing
那就是我拥有的atm代码,减去了在顶部声明的数据库连接。
理想情况下,我只是要更改strSQL部分。
谢谢你的帮助
这样的事情将为您完成这项工作:
Dim strSQL As String strSQL = "" Dim hnd As Integer hnd = FreeFile Open "C:\Temp\yourScript.sql" For Input As hnd Dim row As String Do Until EOF(hnd) Line Input #hnd, row strSQL = strSQL & row & vbNewLine Loop Close #hnd