VBA Excel SumIf返回0

时间:2017-11-09 09:30:18

标签: vba excel-vba excel

我在下面的代码中使用SumIf函数来计算第308列(=找到的地方)中所有字符串ValSrc(=要查找的内容)的第309列中的总和(=总和)。代码不会导致运行时错误,但是应该有结果Excel只返回0。

On Error GoTo Errorhandler
ValSrc = Cells(a, 48).Value & "/DIR/" & Cells(4, a).Value
ValFnd = Application.WorksheetFunction.SumIf(Range(Cells(5, 309), Cells(105673, 309)), Range(Cells(5, 308), Cells(105673, 308)), ValSrc)
Cells(a, b) = ValFnd

编辑:

Sub Gewichte_SumIf()

Dim a As Integer, b As Integer
Dim ValSrc As Variant, ValFnd As Double

For a = 5 To 5
    For b = 49 To 300
        If Cells(a, 306) > 0 Then
            If Cells(3, b) = Cells(a, 33) Then
                On Error GoTo Errorhandler
                'ValSrc = .Cells(a, 48).Value & "/DIR/" & .Cells(4, a).Value
                With Worksheets("DS_(2)_Abfragen")
                    Val Fnd = Application.WorksheetFunction.SumIf(.Range(.Cells(5, 309), .Cells(105673, 309)), .Range(.Cells(5, 308), .Cells(105673, 308)), "53.541331,10.033631<53.4977094,10.1118412<52.9314509,9.2331748<monday/DIR/39454")
                    .Cells(a, b) = ValFnd
                End With
            Else
                Cells(a, b) = ""
            End If
        Else
        End If
    Next b
Next a

Exit Sub

Errorhandler:
Cells(a, b) = 0
Resume Next

End Sub

2 个答案:

答案 0 :(得分:1)

SumIf的参数是:

  1. 搜索范围
  2. 标准
  3. 总和范围
  4. 所以你应该使用

    ValFnd = Application.WorksheetFunction.SumIf(Range(Cells(5, 308), Cells(105673, 308)), _
                                                 ValSrc, _
                                                 Range(Cells(5, 309), Cells(105673, 309)))
    

答案 1 :(得分:0)

使用.Cells.Range参阅正确的工作表。像这样:

With Worksheets("Name-Of-Worksheet")
    ValSrc = .Cells(a, 48).Value & "/DIR/" & .Cells(4, a).Value
    ValFnd = Application.WorksheetFunction.SumIf(.Range(.Cells(5, 309), .Cells(105673, 309)), .Range(.Cells(5, 308), .Cells(105673, 308)), ValSrc)
    .Cells(a, b) = ValFnd
End With

如果你不这样做,它需要ActiveSheet,可能这不是你需要的。

This is the documentation of the function.

&#34;代码没有导致运行时错误,但是应该有结果Excel只返回0。&#34; - 由于On Error GoTo Errorhandler,它返回0。删除此行并查看运行时错误。