且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试删除命名范围时出现VBA 400错误

更新时间:2022-04-29 09:16:05

好,经过长时间的聊天和反复试验,我发现了问题所在.实际上是两倍.

Ok, after a long chat and some trial and error I've found the problem. It's actually two-fold.

此代码不起作用的原因似乎是因为它找到的第一个命名范围是Excel内置范围,显然无法删除.这两个代码段都是这种情况

The reason this code didn't work, seems to be because the first Named Range it found was an Excel built-in range which obviously couldn't be deleted. This is the case with both code snippets

Dim xName As Name
For Each xName In Application.ActiveWorkbook.Names
    xName.Delete
Next

AND

Dim xName As Name
For Each xName In Application.ActiveWorkbook.Names
    If InStr(xName.Name, "!") = 0 Then xName.Delete
Next

因为这两个原因都找到了内置的命名范围"_xlfn.CONCAT",并试图将其删除.

Because both of these find that built-in Named Range "_xlfn.CONCAT" and tries to delete it.

我终于听了@QHarr的建议,并使用了另一个限定词.幸运的是,我在工作簿合并范围"中的所有命名范围的名称都带有"Master",因此很容易.

I finally heeded @QHarr's advice and used a different qualifier. Luckily all my Named Ranges in the Workbook Scope has "Master" in the name, so it was easy enough.

那么,最终的解决方案:

Dim xName As Name
For Each xName In Application.ActiveWorkbook.Names
    If InStr(xName.Name, "Master") > 0 Then xName.Delete
Next

感谢大家!