如何查找正在查找的列时如何处理错误

时间:2015-07-07 03:54:23

标签: vba excel-vba excel

执行此代码时出现此运行时错误13:

Dim rng As Range, rngx As Range
Dim LastRow As Long, LastRowx As Long
Dim col As Long, colx As Long
Dim a As Double, b As Double

With ActiveSheet

    Set rng = Sheets("COMPAS").Range("A9:" & .Range("ZZ9").End(xlToRight).Address)
    col = Application.Match("*COMMUNICATIONS*", rng, 0)
    LastRow = Sheets("COMPAS").Cells(1000000, col).End(xlUp).Row

End With

a = Sheets("COMPAS").Cells(LastRow, col)


With ActiveSheet

    Set rngx = Sheets("COMPAS").Range("A9:" & .Range("ZZ9").End(xlToRight).Address)
    colx = Application.Match("*SLOPCHEST*", rng, 0)
    LastRowx = Sheets("COMPAS").Cells(1000000, col).End(xlUp).Row

End With

b = Sheets("COMPAS").Cells(LastRowx, colx)

Sheets("MACRO TEMPLATE").Cells(11, 2) = a + b 

我的代码找到了列" COMMUNICATIONS"并确定其最后一行值。与#34; SLOPCHEST"列相同。如果"通讯"缺少,那么该值将是" SLOPCHEST"只有,反之亦然。如果两个列都在那里,那么它将被添加。

我的问题是当列"通讯"或者" SLOPCHEST"缺少,它给了我一个错误。如何处理错误列时的错误,它仍然会给我我想要的结果。

1 个答案:

答案 0 :(得分:0)

您可以尝试捕获 no Match。

产生的错误
col = Application.Match("*COMMUNICATIONS*", rng, 0)
If IsError(col) Then
    'not found
Else
    'do what you want         
End If

colx = Application.Match("*SLOPCHEST*", rng, 0)
If IsError(colx) Then
    'not found
Else    
    'do what you want, set a value you need        
End If

如果未找到这两个值,您可能需要设置默认值或根据您的要求进行分配。 the docs