评估sumproduct

时间:2015-10-15 05:07:11

标签: excel excel-vba excel-formula vba

我无法在代码末尾评估sumproduct。我认为其他一切正常,但我一直在努力

  

类型不匹配错误

我尝试了各种各样的语法变体,但仍然无法使其工作。有什么想法吗?

Sub Sample()
    Dim ws As Worksheet
    Dim x As Long
    Dim lRow As Long, llRow As Long
    Dim aCell As Range, bCell As Range
    Dim rng1 As Range, rng2 As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    With ws
        Set aCell = .Range("B6:E20").Find(Cells(14, 9).Offset(0, -1).Value)
        If Not aCell Is Nothing Then
            lRow = .Range(Split(.Cells(, aCell.Column).Address, "$")(1) & .Rows.Count).End(xlUp).Row
            If lRow > 1 Then
                Set rng1 = .Range(aCell.Offset(1), .Cells(lRow, aCell.Column))
            End If
        End If

        Set bCell = .Range("B6:E20").Find(Cells(14, 9).Offset(-1, 0).Value)
        If Not bCell Is Nothing Then
             llRow = .Range(Split(.Cells(, bCell.Column).Address, "$")(1) & .Rows.Count).End(xlUp).Row
            If llRow > 1 Then
                Set rng2 = .Range(bCell.Offset(1), .Cells(lRow, bCell.Column))
            End If
        End If

        Debug.Print rng1.Address
        Debug.Print rng2.Address

        x = Evaluate("=sumproduct(""rng1"",""rng2"")")
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

rng1rng2Sumproduct函数没有任何意义,因为它不是Named Range或有效范围地址。所以Evaluate函数失败了。

要使其正常工作,请尝试:

x = Evaluate("=sumproduct(" & rng1.Address & "," & rng2.Address & ")")

现在为了确保评估正确的范围,您可能需要将地址属性的外部参数设置为 True 。< / p>

x = Evaluate("=Sumproduct(" & rng1.Address(, , , True) & _
    "," & rng2.Address(, , , True) & ")")