我今天写了一些代码用于工作,我遇到了一个问题,我通过VBA提供SQL服务器的命令并没有征求相同数量的信息,就好像我要执行相同的操作一样服务器本身的命令。如果我在VBA中执行下面的代码,我会得到大约25行的68列。如果我在服务器本身上执行相同的命令,那么我只能获得超过1500行的68列。我正在做的是在表单中选择订单号或日期,并将大量数据剥离到我的客户想要查找的内容。我确定这不是在电子表格中分发数据的最佳方式。我正在寻找建议和错误更正!
提前致谢,
亚当
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
constr = "Provider=REMOVEDFORPRIVACY"
If (ComboBox1.Value <> "" And ComboBox2.Value <> "") Or (ComboBox1.Value = "" And ComboBox2.Value = "") Then
MsgBox "Please select one search method.", vbOKOnly
ComboBox2.Value = ""
ComboBox1.Value = ""
ElseIf (ComboBox1.Value <> "" And ComboBox2.Value = "") Then
cmd.CommandText = "SELECT * FROM [Run_Data].[dbo].[RunLog_Data] WHERE SnapShot_Date = '" & ComboBox1.Value & "'"
conn.Open constr
cmd.ActiveConnection = conn
Set rst = cmd.Execute()
Do While Not rst.EOF
o = o + 1
If o > 67 Then
o = 1 'Column Position
n = n + 1 'Row Position
End If
Range(Cells(n, o), Cells(n, o)).Value = rst(o)
rst.MoveNext
Loop
rst.Close
conn.Close
ElseIf (ComboBox1.Value = "" And ComboBox2.Value <> "") Then
cmd.CommandText = "SELECT * FROM [Run_Data].[dbo].[RunLog_Data] WHERE OrderNumber = '" & ComboBox2.Value & "'"
conn.Open constr
cmd.ActiveConnection = conn
Set rst = cmd.Execute()
Do While Not rst.EOF
'Duplicate above and consolidate code
rst.MoveNext
Loop
rst.Close
conn.Close
End If
答案 0 :(得分:2)
您遇到的问题是,在填写每个单元格后,您正在执行rst.MoveNext
。因此,在第一行输出中,您将获取第一个记录的第一列,第二个记录的第二列,......第68个记录的第68列。然后使用第69条记录的第1列填充第二行输出
我相信你可以用
替换你的整个循环Cells(1,1).CopyFromRecordset rst
(将Cell(1,1)替换为您希望成为结果左上角的任何单元格)
但您也可以在If语句中移动rst.MoveNext
命令,即
If o > 67 Then
o = 1 'Column Position
n = n + 1 'Row Position
rst.MoveNext
End If
答案 1 :(得分:0)
Private Sub acceptButton_Click()
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
constr = "REMOVEDFORPRIVACY"
Dim sel_str, sel_type As String
If (ComboBox1.Value <> "" And ComboBox2.Value <> "") Or (ComboBox1.Value = "" And ComboBox2.Value = "") Then
MsgBox "Please select one search method.", vbOKOnly
ComboBox2.Value = ""
ComboBox1.Value = ""
ElseIf (ComboBox1.Value <> "" And ComboBox2.Value = "") Then
sel_type = "SnapShot_Date"
sel_str = ComboBox1.Value
ElseIf (ComboBox1.Value = "" And ComboBox2.Value <> "") Then
sel_type = "OrderNumber"
sel_str = ComboBox2.Value
End If
cmd.CommandText = "SELECT * FROM [Run_Data].[dbo].[RunLog_Data] WHERE " & sel_type & " = '" & sel_str & "'"
conn.Open constr
cmd.ActiveConnection = conn
Set rst = cmd.Execute()
Cells(2, 1).CopyFromRecordset rst
rst.Close
conn.Close
Me.Hide
End Sub