如何在VBA中显示行和列值以进行选择查询

时间:2016-05-17 18:44:15

标签: vba excel-vba excel

我的实际代码如下:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
                Call extract
            End Sub
            Private Sub Worksheet_SelectionChange(ByVal Target As Range)
            End SubSub extract()
            Dim cn As Object
                    Dim uid1, pass1, srvrnm --pass parm
            Set cn = CreateObject("ADODB.Connection")
            Dim rs As Object
            Set rs = CreateObject("ADODB.Recordset")
            Dim cmdSQLData As Object
            Set cmdSQLData = CreateObject("ADODB.Command")
            uid1 = "SSSS"   --user-id
            pass1 = "JJJJ"  --pass words
            srvrnm = "JJJJSDS" --server name
            On Error GoTo err1
            cn.Open "Driver=Teradata; DBCName="& srvrnm& ";uid="& uid1& ";AUTHENTICATION=ldap;pwd="& pass1& "; Trusted_Connection=True"
            Set cmdSQLData.ActiveConnection = cn
            On Error Resume Next
            query1 = "select tablename,databasename as xx from DBC.TABLES sample 2;"
            cmdSQLData.CommandText = query1
            cmdSQLData.CommandTimeout = 0
             Set rs = cmdSQLData.Execute()
            Sheet1.Cells(2, 1) = rs.Fields(0).Value
            Set rs = Nothing
            err1:
            End Sub

我的问题是如何在excel行和列中获取数据库表结果,其行数与表中的行数和后续列数一样

2 个答案:

答案 0 :(得分:0)

您需要遍历记录集并显示数据。所以你有这个:

    Set rs = cmdSQLData.Execute()
    Sheet1.Cells(2, 1) = rs.Fields(0).Value
    Set rs = Nothing

你需要这样的东西:

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 = 3 '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

关于注释:要添加字段标题,您需要创建一个初始循环,而不是移动到下一条记录。请参阅上面的修改后的代码。

答案 1 :(得分:0)

将整个记录集复制到Excel工作表的最快方法应该是:

Sheet1.Cells(2, 1).CopyFromRecordset rs