将参数传递给excel vba中的过程时出错

时间:2017-01-08 16:29:25

标签: excel vba excel-vba

Sub sumtotal_of_month()
Dim a As Integer
a = 0

For i = 2 To 365
    If (Sheets("Sheet1").Range("F" & i).Value = 1 And Sheets("Sheet1").Range("D" & i).Value <> "") Then
    a = a + Sheets("Sheet1").Range("D" & i).Value
End If
Next i
MsgBox (a)
End Sub

上面的代码运行正常,但当我尝试用参数替换“1”时,它不会提供任何输出。这段代码非常业余,因为我只是一个初学者。我使用Excel 2007。

Sub sumtotal_of_month(month As Integer)
Dim a As Integer
a = 0

For i = 2 To 365
    If (Sheets("Sheet1").Range("F" & i).Value = month And Sheets("Sheet1").Range("D" & i).Value <> "") Then
    a = a + Sheets("Sheet1").Range("D" & i).Value
End If
Next i
MsgBox (a)
End Sub

1 个答案:

答案 0 :(得分:0)

鉴于您必须检查您作为month参数传递给您的sub的值,您可以按如下方式简化您的sub:

Sub sumtotal_of_month(month As Integer)
    Dim a As Double

    With Worksheets("Sheet1")
        a = WorksheetFunction.SumIf(.Range("F2:F365"), month, .Range("D2:D365"))
    End With
    MsgBox a
End Sub