有一个愚蠢的问题,它看起来很简单,但我就是不明白。
得到了一个非常简单的 Excel 工作表 vba 代码:
Private Sub GET_MDW_DATA()
On Error GoTo ErrorHandler
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim cmdSQLData As ADODB.Command
Set cmdSQLData = New ADODB.Command
Dim cnstr As String
Dim usr
Set usr = Nothing
usr = Sheet1.Cells(1, 4).Value
Dim pwd
Set pwd = Nothing
pwd = Sheet1.Cells(2, 4).Value
Dim odbcname
Set odbcname = Nothing
odbcname = Sheet1.Cells(1, 8).Value
Dim Category As String
Category = Sheet1.Cells(1, 6).Value
Dim Store As String
Store = Sheet1.Cells(2, 6).Value
cnstr = "Data Source=" & odbcname & "; Database=belccp_msi_d; Persist Security Info=True; User ID=" & usr & "; Password=" & pwd & "; Session Mode=ANSI;"
cn.Open cnstr
Set cmdSQLData.ActiveConnection = cn
Sheet1.Range("A6 : H1000000").Clear
Query = "SELECT SOMETHING FROM SOME DATABASE"
cmdSQLData.CommandText = Query
cmdSQLData.CommandType = adCmdText
cmdSQLData.CommandTimeout = 0
Set rs = cmdSQLData.Execute()
rs.MoveFirst
x = 6
Do While (rs.BOF = False or rs.EOF = False)
p = rs.GetRows(-1)
Sheet1.Range("A" & x).Value = p(0, 8)
Sheet1.Range("B" & x).Value = p(1, 8)
Sheet1.Range("C" & x).Value = p(2, 8)
Sheet1.Range("D" & x).Value = p(3, 8)
Sheet1.Range("E" & x).Value = p(4, 8)
Sheet1.Range("F" & x).Value = p(5, 8)
Sheet1.Range("G" & x).Value = p(6, 8)
Sheet1.Range("H" & x).Value = p(7, 8)
x = x + 1
Loop
cn.Close
Set cn = Nothing
Set rs = Nothing
Set cmdSQLData = Nothing
如果我“打印”我的选择,复制它并在查询中执行它,它会从我的数据库中返回 30 行,但是当我从我的 excel“代码”中执行它时,它只返回 1 行,30 行中只返回一行。
我已经检查过了,就在x=x+1
isrs.EOF
之前True
。这意味着要么我的记录集只有一个值(如果是,为什么?因为我的选择返回 30 行)或者我没有正确解析它。有什么提示吗?
提前谢谢了,