简体   繁体   English

如果不是ActiveSheet.Range()是什么都没有找到任何错误

[英]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. 文本文件中有一些我不需要的数据,所以如果sub找不到匹配的单元格,则只是想忽略它。

But, when the function finds a Defined Name that doesn't exist it throws an 1004 error. 但是,当函数找到不存在的定义名称时,它会抛出1004错误。 Putting On Error Resume Next after the Do While Not fixes the problem, but that is more of a band-aid solution. Do While Not修复问题之后On Error Resume Next ,但这更像是一个创可贴解决方案。

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: 我也试过这个版本的函数,它仍然会导致1004错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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