VBA Sumifs多个打开的工作簿和条件

时间:2019-02-20 22:35:47

标签: excel vba

我试图对外部工作簿中列中的所有数据求和,不存在NA值,并且我的公式仅返回零。

总和范围:全局文件列EU4:EU 条件1范围:全局文件列L4:L 条件1:ForecastBI:B列 条件2范围:全局文件列K4:K 准则2:ForecastBI:C列 准则3范围:“全局文件”列KY4:K 条件3:ForecastBI:D列

Dim Master As Excel.Worksheet: Set Master = Application.Workbooks(" 
Global_File.xlsm").Worksheets("data")
Dim LrHc As Long: LrHc = Master.Cells(Rows.Count, "A").End(xlUp).Row
Dim LcHc As Long: LcHc = Master.Cells(5, Columns.Count).End(xlToLeft).Column 
+ 1

Dim ForecastBI As Excel.Worksheet: Set ForecastBI = 
Application.Workbooks("Actual.xlsm").Worksheets("Act")
Dim LrUpload As Long: LrUpload = ForecastBI.Cells(Rows.Count, 
"A").End(xlUp).Row
Dim LcUpload As Long: LcUpload = ForecastBI.Cells(2, 
Columns.Count).End(xlToLeft).Column + 1

'''Sum range
Dim Fte1 As Excel.Range: Set Fte1 = Master.Range("EU4:EU" & LrHc)

Dim Country As Excel.Range: Set Country = Master.Range("L4:L" & LrHc)
Dim CountryCriteria As Range: Set CountryCriteria = ForecastBI.Range("B2:B" & 
LrUpload)

Dim Region As Excel.Range: Set Region = Master.Range("K4:K" & LrHc)
Dim RegionCriteria As Range: Set RegionCriteria = ForecastBI.Range("C2:C" & 
LrUpload)

Dim DB As Excel.Range: Set DB = Master.Range("KY4:KY" & LrHc)
Dim DBCriteria As Range: Set DBCriteria = ForecastBI.Range("D2:D" & LrUpload)

For x = x To LrUpload

If ForecastBI.Cells(x, 1) = Master.Cells(2, 55) Then
   Cells(x, 8).Value = Application.Worksheetfunction.SumIfs(Fte1, _
      Country, CountryCriteria.Cells(x, 2).Value, _
      Region, RegionCriteria.Cells(x, 3).Value, _
      DB, DBCriteria.Cells(x, 4).Value)

Else: ForecastBI.Cells(x, 8) = 0

End If

Next x

1 个答案:

答案 0 :(得分:0)

我认为,至少在开始时,执行此类操作的最简单方法是记录步骤,当您单击每个步骤时。我刚做完,然后在下面提出了这个问题。

Sub Macro1()

    ActiveCell.FormulaR1C1 = _
        "=SUMIF([Book1.xlsx]Sheet1!RC:RC,""A"",[Book1.xlsx]Sheet1!RC[1]:RC[5])"
    Range("A1").Select
    Selection.AutoFill Destination:=Range("A1:A10")
    Range("A1:A10").Select

End Sub

作为替代方案,我使用Sumproduct函数。

Sub Macro2()

    Range("A1").Select
    ActiveCell.FormulaR1C1 = _
        "=SUMPRODUCT(([Book1.xlsx]Sheet1!RC=""A"")*([Book1.xlsx]Sheet1!RC[1]:RC[5]))"
    Range("A1").Select
    Selection.AutoFill Destination:=Range("A1:A10")
    Range("A1:A10").Select

End Sub