Sumif返回相同的值

时间:2019-03-18 08:29:56

标签: excel vba

我得到了下面的表格,该表格需要填写基于当月的数据(工作表“ PR”):

enter image description here

原始数据的示例如下所示(工作表“ CSV数据PR”):

enter image description here

我有两个问题:

  • SumIF仅适用于第一个区域,所有其他区域都使用相同的数据。例如,正确的数据显示在2月以下
  • 由于某种原因,它一直将配方推倒了……,而它应该停在西欧。我不确定为什么会这样。

基于以下代码:

Sub TableDataTest()

    Dim rngHdrFound, rngHdrFound2, findrng, USDRng, RegionRNG, rngHeaders, RngHeadersOutPut As Range
    Dim x, y As Worksheet
    Dim ThisMonth As Date
    Dim index As Variant

    Application.ScreenUpdating = False

    'Set Worksheets
    Set x = ThisWorkbook.Sheets("CSV Data PR")
    Set y = ThisWorkbook.Sheets("PR")
    index = y.Range("D8")
    ThisMonth = Format(Date, "MM/YYYY")

    'Set HeaderRow
    Const ROW_HEADERS As Integer = 1

    Set rngHeaders = Intersect(Worksheets("CSV Data PR").UsedRange, Worksheets("CSV Data PR").Rows(ROW_HEADERS))
    Set RngHeadersOutPut = y.Range("6:6")
    Set rngHdrFound = rngHeaders.Find("In USD")
    Set rngHdrFound2 = rngHeaders.Find("Region")
    Set findrng = RngHeadersOutPut.Find(What:=ThisMonth, LookIn:=xlFormulas, lookat:=xlWhole)
    Set USDRng = Range(rngHdrFound.Offset(1), rngHdrFound.End(xlDown))
    Set RegionRNG = Range(rngHdrFound2.Offset(1), rngHdrFound2.End(xlDown))

    'Find CurrentMonth + Range
    With y
        If findrng Is Nothing Then
            MsgBox "Error, unable to match " & ThisMonth & " in the specified range", vbCritical
        Exit Sub
        Else
            findrng.Offset(2, 0).Resize(Selection.Rows.Count + 8).Value = Application.WorksheetFunction.SumIf(RegionRNG, "=" & index, USDRng)
        End If
    End With

    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

Option Explicit
Sub TableDataTest()

    Dim ws As Worksheet, wsData As Worksheet, MonthCol As Integer, ThisMonth As Date, C As Range, _
    x As Integer, y As Integer

    x = 2 'Number of the column with the region
    y = 3 'Number of the column with the data to sum

    With ThisWorkbook
        Set ws = .Sheets("PR")
        Set wsData = .Sheets("CSV Data PR")
    End With
    ThisMonth = Format(wsData.Range("C2"), "MM/YYYY")
    With ws
        MonthCol = .Cells.Find(ThisMonth, LookIn:=xlFormulas, lookat:=xlWhole).Column
        For Each C In .Range(.Cells(3, Col), .Cells(11, Col))
            C = Application.SumIf(wsData.Columns(x), .Cells(C.Row, 1), wsData.Columns(y))
        Next C
    End With

End Sub

您只需要找到表中月份的列,然后对要使用的行进行硬编码,因为据我所知,它们总是相同的,并且不太可能增长。

PS:我假设表从第3行和A列开始,否则更改For Each C范围的开始第3行以及sumif取列1的条件。