获取记录集值而无需复制到工作表(Excel VBA)

时间:2018-06-30 17:35:34

标签: excel vba excel-vba

我正在整理一个用户表单,用户可以在其中从SQL Server实时获取已解决查询的数量。

当前,我使用ADODB连接来连接到SQL表并执行Count命令。然后,我获取该值并将其复制到Admin表中,然后在用户表单中显示该值。

我想知道是否有一种方法可以显示Count命令结果而不先复制到管理表,然后再复制到用户表单?

我当前的代码

Private Sub UserForm_Initialize()
    Set objmyconn = New ADODB.Connection
    Set objmyrecordset = New ADODB.Recordset
    Dim strSQL As String
        objmyrecordset.CursorLocation = adUseClient
        objmyconn.ConnectionString = "Provider=SQLOLEDB; Data Source=Server;Initial Catalog=DB;User ID=User;Password=Pass; Trusted_Connection=no"
        objmyconn.Open
        strSQL = "SELECT COUNT(TempStatus) FROM [DB] WHERE [TempStatus] = 'pinged'"
        Set objmyrecordset.ActiveConnection = objmyconn
        objmyrecordset.Open strSQL
        Sheets("Admin").range("A1").CopyFromRecordset (objmyrecordset)
        Me.Label1 = Sheets("Admin").range("A1").Value
        objmyconn.Close
        Set objmyconn = Nothing
        Set objmyrecordset = Nothing
End Sub

任何建议将不胜感激。谢谢

***编辑****

我修改了代码以将val复制到变量中(测试):

    Private Sub UserForm_Initialize()
        Set objmyconn = New ADODB.Connection
        Set objmyrecordset = New ADODB.Recordset
        Dim strSQL As String
        Dim test as variant
            objmyrecordset.CursorLocation = adUseClient
            objmyconn.ConnectionString = "Provider=SQLOLEDB; Data Source=Server;Initial Catalog=DB;User ID=User;Password=Pass; Trusted_Connection=no"
            objmyconn.Open
            strSQL = "SELECT COUNT(TempStatus) FROM [DB] WHERE [TempStatus] = 'pinged'"
            Set objmyrecordset.ActiveConnection = objmyconn
            objmyrecordset.Open strSQL
            test.CopyFromRecordset (objmyrecordset)
            Me.Label1 = test.Value
            objmyconn.Close
            Set objmyconn = Nothing
            Set objmyrecordset = Nothing
    End Sub

3 个答案:

答案 0 :(得分:2)

您不需要CopyFromRecordset作为一个值

只需将您的计数分配给别名,然后使用记录集中的别名字段名

strSQL = "SELECT COUNT(TempStatus) AS CountRecs FROM [DB] WHERE [TempStatus] = 'pinged'"
Set objmyrecordset.ActiveConnection = objmyconn
objmyrecordset.Open strSQL
test = objmyrecordset!CountRecs
Me.Label1 = test

答案 1 :(得分:2)

"SELECT COUNT(TempStatus) FROM [DB] WHERE [TempStatus] = 'pinged'"的结果仍然是一个记录集。因此,您必须像这样objmyrecordset.fields(0).value来获取记录集的字段的值。这应该给您COUNT的结果。

答案 2 :(得分:1)

您可以尝试这样的事情...

Dim x
x = objmyrecordset.GetRows
Me.Label1 = x(0, 0)