且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

vba中的关联数组如php

更新时间:2023-02-09 16:07:54

您可以将SQL查询转换为打开的工作簿中的工作表(与到任何其他工作簿)。在这种情况下,查询字符串将如下所示:

You can make the SQL query to the worksheet in the opened workbook (the same way as to any other workbook). In this case the query string will be as follows:

SELECT SUM([Training Hours]) AS Myval FROM [data sheet$] WHERE Country = 'USA' AND [Training Status] = 'Completed';

这里是代码

Sub TestSQLRequest()

    Const adOpenStatic = 3
    Const adLockOptimistic = 3
    Const adCmdText = &H1

    Select Case LCase(Mid(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".")))
        Case ".xls"
            strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source='" & ThisWorkbook.FullName & "';Mode=Read;Extended Properties=""Excel 8.0;HDR=YES;"";"
        Case ".xlsm"
            strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source='" & ThisWorkbook.FullName & "';Mode=Read;Extended Properties=""Excel 12.0 Macro;HDR=YES;"";"
    End Select

    With CreateObject("ADODB.Connection")
        .Open strConnection
        With .Execute("SELECT SUM([Training Hours]) AS Myval FROM [data sheet$] WHERE Country = 'USA' AND [Training Status] = 'Completed';")
            Myval = .Fields("Myval")
        End With
        .Close
    End With

    MsgBox Myval

End Sub

在查询字符串中,具有空格的列名称应放在方括号中,以及包含数据的工作表的名称后跟 $
不用说,查询无法访问数据,在对表进行了一些更改后,该数据未保存到文件中。
请注意, Excel 8.0 提供程序将无法在64位Excel版本上工作,尝试使用 Excel 12.0 提供者(第二个 strConnection 赋值)。

Within the query string, the column names with spaces should be put into square brackets, as well as the name of the worksheet containing data followed by $. It goes without saying that the query can't access to the data, which wasn't saved to the file after some changes have been made to the sheet. Note that Excel 8.0 provider won't work on 64-bit Excel version, try to use Excel 12.0 provider instead (the second strConnection assignment).