我通过excel-vba& amp;在excel中运行SQL查询ADO。 我使用循环解析结果 然后,我发现在解析结果之前我必须知道sql将生成多少条记录。
实际上,在生成查询之前,我不知道查询结果记录的数量。
任何函数或方法都可以让我知道,以便我可以使用循环语句?
(我已经了解.Fields().Properties(),但没有工作)
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = ThisWorkbook.FullName
'You can provide the full path of your external file as shown below
'DBPath ="C:\InputData.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLSting = select ....' it is too long so i choose to skip
Set rs = Conn.Execute(sSQLSting)
Do While Not rs.EOF
'Officer = rs.Fields(i).Value
For j = 5 To 29 ' THIS IS THE MAIN CODE I NEED TO IMPROVE
'worksheet1.Cells(7, 11) = rs.Properties.Count
worksheet1.Cells(j, 1) = rs.Fields(0).Value
worksheet1.Cells(j, 3) = rs.Fields(2).Value
worksheet1.Cells(j, 4) = rs.Fields(3).Value
worksheet1.Cells(j, 7) = rs.Fields(6).Value
' Insert data to your worksheet here
rs.MoveNext
Next j
Loop
rs.Close
End Sub
For j = 5 To 29 '
next j
这是我应该设置的影响工作表解析范围的范围。在这种情况下,总共有24个查询记录结果。如果我设置j太大(例如To 30),则会提示输出3021错误 - BOF& EOF应该是真的。因此,范围应该适合记录的数量。
答案 0 :(得分:1)
你不需要j的循环。只需在所有单元格分配之后和do循环结束之前增加j。
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = ThisWorkbook.FullName
'You can provide the full path of your external file as shown below
'DBPath ="C:\InputData.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLSting = select .... ' it is too long so i choose to skip
Set rs = Conn.Execute(sSQLSting)
j = 5
Do While Not rs.EOF
'worksheet1.Cells(7, 11) = rs.Properties.Count
worksheet1.Cells(j, 1) = rs.Fields(0).Value
worksheet1.Cells(j, 3) = rs.Fields(2).Value
worksheet1.Cells(j, 4) = rs.Fields(3).Value
worksheet1.Cells(j, 7) = rs.Fields(6).Value
j = j + 1
rs.MoveNext
Loop
rs.Close
End Sub