简体   繁体   中英

VBA How to Check if Cell Value is valid and exists?

I have this cell.Offset(0, -2) cell that I need to check if it exists inside my VBA loop.

My idea is that if the cell has an .Offset(0, -2) that does not exist (eg say cell = Column B and cell.Offset(0, -2) = Column A-1, cell.Offset(0, -2) is supposed to be invalid), I want to be able to check that it doesn't exist in the if else statement.

Right now when it doesn't exist, I'm getting a “Runtime Error 1004: Application defined or object defined error” .

I've tried IsErr(cell.Offset(0, -2)) , cell.Offset(0, -2).Value , If cell.Offset(0, -2) Is Nothing Then , cell.Offset(0, -2) = "" , but none of them seem to work... can anyone point me in the right direction? I'm pretty new to VBA and it seems like different variable types have different ways of checking if the value exists.

A solution for this is by using the constantly misused On Error Resume Next , coupled with a If IsError . Here's an example:

On Error Resume Next
If IsError(ActiveCell.Offset(, -2).Select) = True Then
    'This is indicative of an error. Meaning you are on Column B, and you ran out of space.
Else
    'This means an error did not occur. Meaning you were at least on Column C or above.
End If

There may be a better solution, in fact I am sure there is. But what this will do is allow you to move past the actual 1004 Application error, and you can actually identify, and use the error that was really returned, instead of just forcing your macro/script to end.

To avoid using the error check, you can always check the current column index (B is 2) and make sure whatever you are offsetting by, once subtracted by your index is greater than 0. For example, column B is 2. Your offset is 2. 2 - 2 = 0 , so it should not attempt it. Column C is 3, 3 - 2 = 1 , which is greater than 0 so it would be valid. Both are explorable methods.

If you can use your offset amount as a variable, or some method to evaluate against the cell's column, you don't need to defend against errors. Consider below...

Sub IsvalidARea()
    Dim OffsetAmount As Integer: OffsetAmount = -2
    Dim Cell As Range

If Cell.Column + OffsetAmount < 1 Then
MsgBox "Oh FALSE!"
Else
'EVERYTHING IS OKAY!

End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM