gpt4 book ai didi

excel - If NOT ActiveSheet.Range() Is Nothing 当它什么也没找到时不断出错

转载 作者:行者123 更新时间:2023-12-04 21:50:27 27 4
gpt4 key购买 nike

我有一个读取文本文件并将数据导入到定义名称单元格的子程序。文本文件中有一些我不需要的数据,所以如果子找不到匹配的单元格,它只是假设忽略它。

但是,当函数找到不存在的定义名称时,它会引发 1004 错误。把 On Error Resume NextDo While Not 之后解决了问题,但这更像是一种创可贴的解决方案。

这是引发错误的函数:

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

我也试过这个版本的函数,还是会报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

最佳答案

您必须使用错误处理,因为尝试使用不存在的范围名称会引发错误。

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

关于excel - If NOT ActiveSheet.Range() Is Nothing 当它什么也没找到时不断出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55456615/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com