2

我正在尝试SUMPRODUCT在 VBA 中使用以下公式:

=SUMPRODUCT(--('Sheet 1'!$C$2:$C$10="OK"),(MONTH(Sheet1!$A$2:$A$10)=MONTH($B3))*(YEAR(Sheet1!$A$2:$A$10)=YEAR($B3))*(MONTH(Sheet1!$B$2:$B$10)=MONTH(C$2))*(YEAR(Sheet1!$B$2:$B$10)=YEAR(C$2)))

我的工作簿与航班预订有关,它由两张表组成,表 1 和表 2。具体而言:

表 1 包括示例数据:

| Booking date | Check-in date | Status |
|--------------|---------------|--------|
| 25-Sep-18    | 18-May-19     | OK     |
| 26-Sep-18    | 05-Jul-19     | OK     |
| 26-Sep-18    | 18-Jun-19     | OK     |
| 01-Oct-18    | 19-Jun-19     | OK     |
| 01-Oct-18    | 18-May-19     | OK     |
| 02-Oct-18    | 19-Apr-19     | OK     |
| 03-Oct-18    | 18-May-19     | CL     |
| 06-Oct-18    | 14-May-19     | CL     |
| 07-Oct-18    | 17-Jun-19     | OK     |

SUMPRODUCT而表 2 包括与公式相关的分析输出:

| Booking/Check-in | Apr-19 | May-19 | Jun-19 | Jul-19 |
|------------------|--------|--------|--------|--------|
| Sep-18           |        | 1      | 1      | 1      |
| Oct-18           | 1      | 1      | 2      |        |

我按照@Rosetta 和@Foxfire And Burns And Burns 的建议修复了错误'13' - 类型不匹配。我还按照@JvdV 的建议添加了 Else。现在代码如下所示:

    Dim bk As Worksheet
    Set bk = Worksheets("Sheet 1")

    For Z = 2 To 3
        For j = 2 To 5
            For i = 2 To 10
        If bk.Cells(i, 3).Value = "OK" Then
        If Month(bk.Cells(i, 1)) = Month(Cells(Z, 1)) Then
        If Year(bk.Cells(i, 1)) = Year(Cells(Z, 1)) Then
        If Month(bk.Cells(i, 2)) = Month(Cells(1, j)) Then
        If Year(bk.Cells(i, 2)) = Year(Cells(1, j)) Then

        Range(Cells(j, Z)).Value = Range(Cells(j, Z)).Value + 1

Else Next i
        End If
        End If
        End If
        End If
        End If

    Next j
    Next Z

    End Sub

现在我得到Next without For编译错误。有任何想法吗?

4

1 回答 1

2

您还可以使用.EvaluateSUMPRODUCT公式中获取结果,因为您想将公式集成到 VBA 中。我已经重写了您的一些代码,使其也更具动态性。这样,您可以在 sheet1 上拥有动态行数,在 sheet2 上拥有动态行数和列数。请看下面的代码:

Sub Test()

Dim rng1 As Range, rng2 As Range, rng3 As Range
Dim lr1 As Long, lr2 As Long, lc As Long, x As Long, y As Long

With ThisWorkbook.Sheets("Sheet1")
    lr1 = .Cells(.Rows.Count, "A").End(xlUp).Row
    Set rng1 = .Range("A2:A" & lr1)
    Set rng2 = .Range("B2:B" & lr1)
    Set rng3 = .Range("C2:C" & lr1)
End With

With ThisWorkbook.Sheets("Sheet2")
    lr2 = .Cells(.Rows.Count, "A").End(xlUp).Row
    lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
    For x = 2 To lc
        For y = 2 To lr2
            .Cells(y, x).Value = .Evaluate("=SUMPRODUCT(--(Sheet1!" & rng3.Address & "=""OK""),((MONTH(Sheet1!" & rng1.Address & ")=" & Month(.Cells(y, 1)) & ")*(YEAR(Sheet1!" & rng1.Address & ")=" & Year(.Cells(y, 1)) & "))*((MONTH(Sheet1!" & rng2.Address & ")=" & Month(.Cells(1, x)) & ")*(YEAR(Sheet1!" & rng2.Address & ")=" & Year(.Cells(1, x)) & ")))")
        Next y
    Next x
End With

End Sub

For ... Next除了通过 sheet2 上的所有行和列的动态循环之外,这将删除所有这些循环。

我希望你明白发生了什么。如果您有任何问题,请随时提问。确保相应地调整工作表的名称!

于 2019-08-22T08:02:49.987 回答