程序不能仅作为子函数运行

时间:2019-02-27 20:19:58

标签: excel vba

下面的代码应该设置每个客户的每小时费率,并按照电子表格的长度进行计算,计算每个客户欠我的总金额,然后将该值返回到单元格中,因为我的工作方式是自由职业者。自从我在程序中添加了“费率”功能以来,当前无法运行的代码。在excel电子表格中,我得到的错误看起来像这样#VALUE!。我没有解释为什么会这样。

Function clientCalc(client As String, rate As Integer)
    Dim tbl As ListObject
    Dim tableLen As Double
    Dim sh As Worksheet
    Dim tally As Double
    Set sh = ThisWorkbook.Sheets("Hours")
    Set tbl = sh.ListObjects("Main")
    tableLen = tbl.Range.Rows.Count
    tally = 0
    For i = 2 To tableLen
        If Range("H" & i).Value = client Then
            sh.Range("B" & i).Formula = "=A" & i & "*" & rate & "*24"
            tally = tally + Range("D" & i).Value
        End If
    Next i
    clientCalc = Format(tally, "Currency")
End Function

为了使我能够以某种方式进行这项工作,我必须在上面制作程序并将其转换为Sub而不是Function。在那种情况下,我发现这很好用...

Sub setRate(client As String, rate As Double)
    Dim tbl As ListObject
    Dim tableLen As Double
    Dim sh As Worksheet
    Dim tally As Double
    Set sh = ThisWorkbook.Sheets("Sheet1")
    Set tbl = sh.ListObjects("Table3")
    tableLen = tbl.Range.Rows.Count
    tally = 0
    For i = 2 To tableLen
        If Range("C" & i).Value = client Then
            sh.Range("B" & i).Formula = "=A" & i & "*" & rate & "*24"
        End If
    Next i
End Sub

Sub main()
    Call setRate("Client_One", 30)
    Call setRate("Client_Two", 40)
End Sub

Function clientCalc(client As String)
    Dim tbl As ListObject
    Dim tableLen As Double
    Dim sh As Worksheet
    Dim tally As Double
    Set sh = ThisWorkbook.Sheets("Hours")
    Set tbl = sh.ListObjects("Main")
    tableLen = tbl.Range.Rows.Count
    tally = 0
    For i = 2 To tableLen
        If Range("H" & i).Value = client Then
            tally = tally + Range("D" & i).Value
        End If
    Next i
    clientCalc = Format(tally, "Currency")
End Function

0 个答案:

没有答案