试图找到一种方法防止在Excel VBA中发生类型不匹配错误

问题描述 投票:0回答:1
Sub Calculate_NNA_NMEXRegionUnits_Pacific()
Dim a, rand, AsInteger As Integer
For a = 8 To 42 
 Cells(26, a) = Round(Cells(27, a) * Cells(27, 7) * (Cells(22, 2) - Cells(22, 3) - Cells(20, 7)), 0)
Next a

我正在制作一个程序,在一个范围(26,a)上执行一组计算。公式数据类型是变量/整数,而范围上的数据类型是变量/对象/范围。我很好奇,如果我能确保这个等式的两边都是相同的数据类型,我正在寻找改变公式的方法,我也使用了类型转换公式。我没有成功。我正在寻求帮助以防止在第4行发生类型不匹配,以便我的代码可以继续。

rerand1:
    rand = Application.WorksheetFunction.RandBetween(9, 27) 'Excludes base trim in random addition because of restrictions
    If Cells(27, rand) = 0 Then
        GoTo rerand1 'Wont change a 0 value, because it might be intentionally zero.
    Else
        If Cells(26, 7) < Cells(22, 2) - (Cells(22, 3) + Cells(20, 7)) Then Cells(26, rand) = Cells(26, rand) + 1 'If there is less than the total, add.
        If Cells(26, 7) > Cells(22, 2) - (Cells(22, 3) + Cells(20, 7)) Then Cells(26, rand) = Cells(26, rand) - 1 'If there is more than the total, subtract.
    End If
End If
End Sub

如果需要解决问题,这是我的代码的下一步

excel vba type-mismatch
1个回答
1
投票

Type mismatch不仅可能因为您有不同的值类型而发生。如果该单元格中存在公式错误,您也可以获得该错误。例如,如果您在单元格=0/0中键入A1,然后在即时窗口中键入?Val([A1].value),则会得到Type Mismatch错误。

这是实现您想要的一种方式。尝试将值存储在临时变量中,然后将其用于比较。

Dim tmpVal As Integer

rand = Application.WorksheetFunction.RandBetween(9, 27)

On Error Resume Next
tmpVal = Cells(27, rand)
On Error GoTo 0

If tmpVal = 0 Then

Else

End If
© www.soinside.com 2019 - 2024. All rights reserved.