我正在研究远程服务器上的数据库,并将我的结果放在excel电子表格中。在A栏中说。
因此,我创建了一个按钮,允许“随意”操作并开始设置我的ADODB对象。
与数据库的连接很好,但是我很不清楚如何设置.Recordset对象(MyOutput)以在A列中输出我的查询结果。这是我的代码:
Private Sub RunQuery_Click()
Dim MyOutput As ADODB.Recordset
Dim cnn As New ADODB.Connection
Dim myCommand As ADODB.Command
Dim stringSQL As String
Dim stringConn As String
cnn.Provider = "Microsoft.Jet.OLEDB.4.0;"
cnn.Properties("Jet OLEDB:System database") = "My path"
stringConn = "Data Source=\'my path';User Id='';Password='';"
cnn.Open stringConn
Set myCommand = New ADODB.Command
myCommand.ActiveConnection = cnn
stringSQL = " My query"
myCommand.CommandText = stringSQL
myCommand.Execute
cnn.Close
Set cnn = Nothing
End Sub
我可以在这里帮忙吗?
非常感谢您的时间!
答案 0 :(得分:1)
您可以使用以下内容来执行此操作:
Public Sub RunQuery_Click()
Dim oDB As ADODB.Connection
Dim oCM As ADODB.Command
Dim oRS As ADODB.Recordset
Dim strConn As String
Set oDB = New ADODB.connectoin
With oDB
.Provider = "Microsoft.Jet.OLEDB.4.0;"
.Properties("Jet OLEDB:System database") = "My path"
strConn = "Data Source=\'my path';User Id='';Password='';"
.Open strConn
End With
Set oCM = New ADODB.Command
With oCM
.ActiveConnection = oDB
.CommandText = "My Query"
.CommandType = adCmdText
Set oRS = .Execute
End With
Sheets(1).Range("A1").CopyFromRecordset oRS
oRS.Close
Set oRS = Nothing
oDB.Close
Set oDB = Nothing
End Sub
或者,如果您还想返回字段名称,可以使用:
Public Sub RunQuery_Click()
Dim oDB As ADODB.Connection
Dim oCM As ADODB.Command
Dim oRS As ADODB.Recordset
Dim strConn As String
Dim iCols As Long
Set oDB = New ADODB.connectoin
With oDB
.Provider = "Microsoft.Jet.OLEDB.4.0;"
.Properties("Jet OLEDB:System database") = "My path"
strConn = "Data Source=\'my path';User Id='';Password='';"
.Open strConn
End With
Set oCM = New ADODB.Command
With oCM
.ActiveConnection = oDB
.CommandText = "My Query"
.CommandType = adCmdText
Set oRS = .Execute
End With
For iCols = 0 To oRS.Fields.Count - 1
Sheet(1).Cells(1, iCols + 1).Value = oRS.Fields(iCols).Name
Next
Sheets(1).Range("A2").CopyFromRecordset oRS
oRS.Close
Set oRS = Nothing
oDB.Close
Set oDB = Nothing