如何在VBA脚本中选择2个选择的状态

时间:2016-05-27 09:34:42

标签: vba excel-vba excel

在下面的VBA中我有一个选择有一个表的语句,但我想要多个select语句结果需要在excel中捕获。

Sub extract()

    'usedrows = Sheets("Batch_Creation").Range("A" & Sheets("Batch_Creation").Rows.Count).End(xlUp).Row
    'MsgBox usedrows

    Dim cn As Object
    Dim uid1, pass1, srvrnm
    Set cn = CreateObject("ADODB.Connection")
    Dim rs As Object
    Set rs = CreateObject("ADODB.Recordset")

    Dim cmdSQLData As Object
    Set cmdSQLData = CreateObject("ADODB.Command")
    uid1 = "XXXXX"
    pass1 = "XXXXX"
    srvrnm = "XXXXX"

    On Error GoTo err1
    cn.Open "Driver=Teradata; DBCName=" & srvrnm & ";uid=" & uid1 & ";AUTHENTICATION=ldap;pwd=" & pass1 & "; Trusted_Connection=True"


    Set cmdSQLData.ActiveConnection = cn
    'MsgBox ("1")
    On Error Resume Next
 query1 = "select top 20 * from DBC.TABLES;"   ---first select statements
query2 = "select count(*) from DBC.TABLES;"   ---2nd  select statements
query3 = "select * from DBC.TABLES where columnname="santosh";"   ---3rd  select statements
    'MsgBox query1

        cmdSQLData.CommandText = query1
        cmdSQLData.CommandTimeout = 0
        Set rs = cmdSQLData.Execute()

    Dim r As Integer 'Row
    Dim c As Integer 'Column

    For c = 0 To rs.Fields.Count - 1
        'This will start on Row 1, Column A (due to + 1) and place all the field headers
        Sheet1.Cells(1, c + 1).Value = rs.Fields(c).Name
    Next c
    r = 2 'We'll start on Row 3
    Do While Not rs.EOF
        For c = 0 To rs.Fields.Count - 1
            'c + 1 means we're starting on Column 1 (A)
            'If we wanted to start in Column d, we would use c + 4
            Sheet1.Cells(r, c + 1).Value = rs.Fields(c)
        Next
        r = r + 1
        rs.MoveNext
    Loop
      Set rs = Nothing

    'Set rs = New ADODB.Recordset
    'rs.Clear

    err1:

    End Sub

如何在上述脚本中调用多个select语句

query2 = "select count(*) from DBC.TABLES;"   ---2nd  select statements
query3 = "select * from DBC.TABLES where columnname="santosh";"   ---3rd 

1 个答案:

答案 0 :(得分:0)

每个查询使用记录集是否有问题?

query1

rs1 query2

rs2 query3

rs3

另一种方法 - 通过执行query1收集记录集的数据,然后执行所需的所有操作(复制,粘贴......)。

之后您将 cmdSQLData.CommandText 更改为 query2 ,执行上述所有操作。

再次将 CommandText 更改为 query3