我需要您的帮助,以便使用VBA在Microsoft Excel中构建分析。
我有一个带有y列和n行的数据表
Line Number Firstname Lastname Country Training Hours Training Status 1 John Smith USA 1 Completed 2 Henri Dupont France 1 Completed 3 Paul Walker USA 25 Incomplete 4 Ron Howard USA 10 Completed
而且我想在php中使用数组,但使用VBA
For i = 1 To nblines If(array[i]["Country"] = "USA" And array[i]["Training Status"] = "Completed") Then myval = myval + array[i]["Training Hours"] End If Next
myval应该是11
不幸的是我找不到解决方案。我尝试过字典,集合和数组,但是没有成功。任何的想法?
您可以对打开的工作簿中的工作表进行SQL查询(与其他任何工作簿相同)。在这种情况下,查询字符串将如下所示:
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分配)。
$
Excel 8.0
Excel 12.0
strConnection