VBA:如何解决“类型不匹配”

时间:2019-07-02 21:48:08

标签: 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 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。

1 个答案:

答案 0 :(得分:1)

您所乘的值很可能不是数字,因此必须进行检查。可能的方法是这样的:

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中使用Integer也不是一个好主意,因为您很容易得到溢出错误-Why Use Integer Instead of Long?