简体   繁体   中英

If NOT ActiveSheet.Range() Is Nothing keeps erroring out when it finds nothing

I have a sub that reads a text file and imports data to a Defined Name cell. There is some data in the text file i don't need, so if the sub cannot find a matching cell it is just suppose to ignore it.

But, when the function finds a Defined Name that doesn't exist it throws an 1004 error. Putting On Error Resume Next after the Do While Not fixes the problem, but that is more of a band-aid solution.

Here is the function that is throwing the error:

If Not ActiveSheet.Range(cellName) Is Nothing Then
    Set TxtRng = ActiveSheet.Range(cellName)

    If TxtRng = ActiveSheet.Range(cellName) Then
        TxtRng.Value = getPrice
    End If
End If

I have also tried this version of the function, and it still causes a 1004 error:

If ActiveSheet.Range(cellName) Is Nothing Then
    ''Do Nothing here
Else
    Set TxtRng = ActiveSheet.Range(cellName)

    If TxtRng = ActiveSheet.Range(cellName) Then
        TxtRng.Value = getPrice
    End If
End If

You must use error handling because trying to use a non existent range name throws an error.

Dim TxtRng As Range

Set TxtRng = Nothing 'if you use this code in a loop make sure you initialize it as nothing within your loop. Otherwise you can omit this line.

On Error Resume Next
Set TxtRng = ActiveSheet.Range(cellName)
On Error Goto 0 're-activate error reporting

If Not TxtRng Is Nothing Then
    'your code
End If

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