Excel VBA:如何修复;“类型不匹配”;

Excel VBA:如何修复;“类型不匹配”;,excel,vba,excel-formula,Excel,Vba,Excel Formula,我一直在研究一个简单的宏,它运行一个for循环,将一个单元格乘以列并求和,然后对列中的下一个单元格再次重复。for循环看起来很好,但在尝试将工作表单元格值转换为整数时,它会导致类型不匹配 Dim ws As Worksheet Dim wssum As Worksheet 'set worksheets to copy values Set ws = Sheets("sheet1") Set wssum = Sheets("sheet2") Dim i As Integer Dim j As

我一直在研究一个简单的宏,它运行一个for循环,将一个单元格乘以列并求和,然后对列中的下一个单元格再次重复。for循环看起来很好,但在尝试将工作表单元格值转换为整数时,它会导致类型不匹配

Dim ws As Worksheet
Dim wssum As Worksheet

'set worksheets to copy values
Set ws = Sheets("sheet1")
Set wssum = Sheets("sheet2")

Dim i As Integer
Dim j As Integer
Dim bumonth As Currency
Dim busum As Currency
Dim bux As Currency



'sort through months
For i = 0 To 11
    'sort through rows the number or rows is hardcoded to the number of apps in sheet
    For j = 0 To 43
        bumonth = 0
        bumonth = CCur(ws.Cells(1, 53 + j).Value * ws.Cells(2 + i, 3 + j).Value)
        busum = busum + bumonth
    Next j
       wssum.Cells(4 + i, 3 + j).Value=  busum
    Next i
错误发生在第行

bumonth = CInt(ws.Cells(1, 53 + j).Value * ws.Cells(2 + i, 3 + j).Value)

我希望这段代码能够从表1中的表单中获取值,并将值导出到表2中。

最有可能的是,您要乘以的值不是数字,因此必须对它们进行检查。一种可能的方法如下:

For j = 0 To 43
    If Not IsNumeric(ws.Cells(1, 53 + j).Value) Then
        Err.Raise 999, Description:="Value on  " & ws.Cells(1, 53 + j).Address & " is not numeric!"
    End If
    If Not IsNumeric(ws.Cells(2 + i, 3 + j).Value) Then
        Err.Raise 999, Description:="Value on  " & ws.Cells(2 + i, 3 + j).Address & " not numeric!"
    End If

    bumonth = 0
    bumonth = CCur(ws.Cells(1, 53 + j).Value * ws.Cells(2 + i, 3 + j).Value)
    busum = busum + bumonth
Next j

此外,如评论中所述,在VBA中使用
整数
不是一个好主意,因为您很容易得到溢出错误-

单元格(1,53)和
单元格(2,3)
?在相乘之前,您可能需要转换第一个值中的任何值。如果这两个值的乘积大于
Integer
中允许的限制,则需要将
busum声明为Long
(或
声明为Double
)。您希望将
busum
分配给wssum.Cell.Value,但将其反转<代码>wssum.Cells(4+i,3+j).Value=busum位于代码的最后一行。存储在每个单元格中的值都是较大的货币值,但即使将变量转换为货币,也会出现此错误。感谢您捕捉到bumonth=CInt(ws.Cells(1,53+j).Value*ws.Cells)行中的类型不匹配(2+i,3+j).Value)谢谢你。原来我犯了一个错误,在单元格调用中混淆了我的行和列。这是一个简单的错误,但如果不是因为这个,我会完全忽略。@VBAlearner1234-不客气。调试和查看错误的原因也是编程。