在Excel VBA中将整数与货币相乘
在我的excel表格中,我有一行(第5行)作为项目数量,另一行(第6行)作为项目价格。例如,我想用$56.50乘以200,但这个脚本有问题。谁能帮忙吗在Excel VBA中将整数与货币相乘,excel,visual-studio-macros,vba,Excel,Visual Studio Macros,Vba,在我的excel表格中,我有一行(第5行)作为项目数量,另一行(第6行)作为项目价格。例如,我想用$56.50乘以200,但这个脚本有问题。谁能帮忙吗 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", _
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类型不匹配 图为:
以下是链接:
而且我不能使用=a*b,我必须使用宏 试试这个。记住将第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
你不需要一个循环
您可以在colunm G中使用单次射击范围
- 将G5中的公式添加到用户输入的
中,以测试每行是否出现结果>0(或添加iRownNumber
,以获得结果为0)”
- 用值覆盖公式
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
图中显示数据从第5行开始。前面的行包含文本
因此,请尝试将i=5的设置为iRownNumber
我认为没有必要将Dim i设置为整数,它是在For循环中声明的。但是,当第5行中没有值时,它不起作用。啊,等等,我以为反之亦然。那么只是更改FormatCurrency的位置。请您尝试更新版本的代码,这应该可以工作!你能在邮件中附上那个文件的副本吗?(部分内容)为什么要使用FormatCurrency将值转换为字符串,然后将字符串乘以一个数字?我如何将单元格(i,5)。值和单元格(i,6)。值都转换为双倍,以便可以对它们进行多重化。所有数字(数字、日期、时间、货币等)在Excel中,无论格式如何,它们都作为双精度保存。你不需要做任何转换,特别是当你使用.Value 2而不是.Value+1时。除非你需要循环,否则不要使用循环,也就是说,没有你认为的十分之一。我如何使用循环呢。我还不懂“with”语句,所以你能告诉我如何在for循环中执行它吗?我本可以使用这两个较长的语句,范围(单元格(5,7),单元格(IrownNumber,7))。公式1c1=“=IF(N(RC[-1]*RC[-2]),RC[-1]*RC[-2],””
范围(单元格(5,7),单元格(IrownNumber,7))。值=.Value
。我建议你不要走迂回的路,那样效率很低。如果有帮助的话,我可以更详细地介绍这两行