我有一个问题,我需要我的多行 SQL 查询(仅一列)将结果放入一个单元格。有没有办法做到这一点?
这是我正在使用的代码,我需要将它放入一个单元格的原因是因为在这部分之后我有另一部分代码将一列中的所有单元格写入单独的 XML 文件。
我正在尝试将我的多行查询放入一个单元格中,或者如果可以将其作为变量获取,我可以将其嵌入到我的 XML 创建代码中。
非常感谢所有帮助,如果需要更多信息,请告诉我
Dim adoDbConn As New ADODB.Connection
Dim adoDbRs As New ADODB.Recordset
Dim selectCmd As New ADODB.Command
Dim connstring As String
Dim UID As String
Dim PWD As String
Dim Server As String
' Open connection to the SQL Server database
UID = Worksheets(4).Cells(2, 2).Value 'Username
PWD = Worksheets(4).Cells(3, 2).Value 'Password
Server = Worksheets(4).Cells(4, 2).Value 'Database
connstring = "PROVIDER=MSDAORA.Oracle;DATA SOURCE=" & Server & ";" & "USER ID=" & UID & ";PASSWORD=" & PWD 'Note, I am using MSDAORA as I use an ORACLE DB, you will need to change it for what DB you are using
adoDbConn.Open connstring
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
adoDbConn.CommandTimeout = 900
' Execute the select query
selectCmd.ActiveConnection = adoDbConn
selectCmd.CommandText = Worksheets(1).Cells(ActiveCell.Row, 13).Value
Set adoDbRs = selectCmd.Execute(, , adCmdText)
' Activate the Worksheet
Dim ws As Worksheet
Set ws = Worksheets(1)
ws.Activate
' Put the query results starting from cell N2
If adoDbRs.EOF = False Then ws.Cells(ActiveCell.Row, 14).CopyFromRecordset adoDbRs
' Close the connection and free the memory
adoDbRs.Close
Set adoDbRs = Nothing
Set selectCmd = Nothing
adoDbConn.Close
Set adoDbConn = Nothing