在Excel VBA中将整数与货币相乘

3
在我的Excel表格中,我有一行(第五行)为物品数量,另一行(第六行)为物品价格。例如,我想将200乘以56.50美元,但是我在这个脚本上遇到了问题。请问有谁能帮忙吗?
Sub calcprice()
    Dim i As Integer
    Dim iRowNumber As Integer   ' Integer to store result in
    Dim val As Double

    iRowNumber = InputBox(Prompt:="Number of Rows", _
          Title:="Rows: ", Default:="# of Rows")
    For i = 1 To iRowNumber
        If Cells(i, 5).Value >= 0 And Cells(i, 6).Value >= 0 And IsEmpty(Cells(i, 5)) = False And IsEmpty(Cells(i, 5)) = False Then
            val = FormatCurrency(Cells(i, 5).Value) * Cells(i, 6).Value
            Cells(i, 7).Value = val
        End If
    Next i
End Sub

这里显示“运行时错误13”
类型不匹配 这是图片: it says currency 这是链接:https://www.dropbox.com/s/lla2cuz8hqu5qyp/test.xlsm
而且我不能使用=a*b,我必须使用宏!

1
你为什么要使用FormatCurrency将一个值转换为字符串,然后再将字符串乘以一个数字? - Charles Williams
我该如何将cells(i,5).value和cells(i,6).value都转换为double类型,以便我可以对它们进行乘法运算? - user1796681
Excel中的所有数字(数字、日期、时间、货币等)都以double形式保存,无论它们如何格式化。您不需要进行任何转换,特别是如果您使用.Value 2而不是.Value。 - Charles Williams
3个回答

3

您不需要循环

您可以在列 G 中使用单发射程来处理

  • Adds a formula from G5 to the user entered iRowNumber to test whether a result > 0 happens in each row (or adds "" for a 0 result)
  • overwrite the formulae with the values

    Sub calcprice()
        Dim iRowNumber As Long   ' Integer to store result in        
    iRowNumber = InputBox(Prompt:="Number of Rows", _
          Title:="Rows: ", Default:="# of Rows")
    
    With Range(Cells(5, 7), Cells(iRowNumber, 7))
    .FormulaR1C1 = "=IF(N(RC[-1]*RC[-2]),RC[-1]*RC[-2],"""")"
    .Value = .Value
    End With
    End Sub
    

+1 不必使用循环,除非你需要它们,也就是说不要像你想象的那样频繁地使用它们。 - nutsch
我该怎么用循环来实现它?我还不理解“with”语句,所以你能展示一下如何用for循环来实现吗? - user1796681
与其使用 With,我可以使用这两个更长的语句:Range(Cells(5, 7), Cells(iRowNumber, 7)).FormulaR1C1 = "=IF(N(RC[-1]*RC[-2]),RC[-1]*RC[-2],"""")"Range(Cells(5, 7), Cells(iRowNumber, 7)).Value = .Value。我建议您不要使用循环方式,因为它效率低下。如果需要,我可以更详细地解释这两行代码。 - brettdj

0

试一下这个。记得将第5个单元格和第6个单元格格式化为您喜欢的货币!

    Sub calcprice()

    Dim iRowNumber As Integer
    Dim val As Double


    iRowNumber = InputBox(Prompt:="Number of Rows", _
          Title:="Rows: ", Default:="# of Rows")


    For i = 1 To iRowNumber
        If Cells(i, 5).Value >= 0 And Cells(i, 6) >= 0 Then
            If Cells(i, 6).Value > 0 Then
                val = Cells(i, 5).Value * FormatCurrency(Cells(i, 6).Value)
                Cells(i, 7).Value = val
            End If

        End If
    Next i
End Sub

我认为没有必要使用“Dim i As Integer”,因为它已经在for循环中声明了。 - Artem
然而,当第五行没有值时,它就无法工作。 - Artem
啊,等等,我以为是反过来的。那么只需要改变FormatCurrency的位置就可以了。 - Artem
请尝试使用更新的代码版本,这应该可以工作! - Artem
请问您能否在帖子中包含该文件的副本?(其中的部分) - Artem

0

你有 For i = 1 to iRowNumber

图片显示数据从第5行开始。之前的行包含文本。

因此,请尝试使用 For i = 5 to iRowNumber


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接