VBA 尝试为变量赋值时出现运行时错误 1004“应用程序定义或对象定义错误”

VBA Runtime Error 1004 “Application-defined or Object-defined error” when trying to assign value to a variable

1st 我解释一下我想做什么。我有一个包含许多 sheet 的工作簿,每个工作簿都有许多命名范围。我想遍历特定 sheet 上的命名范围,然后 hide/unhide 它们(如果它具有特定名称)。一开始我想隔离 sheet 但我遇到了问题。我正在尝试获取 sheet 的名称,范围已打开并将该名称分配给变量。这是代码的一部分,我遇到了问题:

Dim rng as Name
Dim shP as String
for each rng in ThisWorkbook.Names
shp = rng.RefersToRange.Parent.Name 'here i get the error
... rest of the code ...

如果我只是 Debug.Print rng.RefersToRange.Parent.Name 而不是在那一行,我会立即 window 打印出 sheet 名称。 我也试过 Dim shP as Variant 但没有用。

提前感谢您的回答。

如果您要获取工作表,则需要使用 Worksheet 对象。

Option Explicit
Sub Test()

    Dim rng As Name
    Dim shP As Worksheet
    For Each rng In ThisWorkbook.Names
        Set shP = rng.RefersToRange.Parent 'here i get the error
    '... rest of the code ...
    Next rng

End Sub

然后您可以像使用工作表一样使用shP

您可能在工作簿中有一个不对应于单元格块的名称。在这里,我将名称 when 分配给公式 =now()

如果我运行:

Sub WhatsInaName()
    Dim nm As Name, s As String

    For Each nm In ThisWorkbook.Names
        MsgBox nm.RefersToRange.Parent.Name
    Next nm

End Sub

我也得到一个1004

你应该先 运行:

Sub listum()

    With ActiveWorkbook
        If .Names.Count > 0 Then
            For i = 1 To .Names.Count
                MsgBox (i & "  " & .Names(i).Name)
            Next
        End If
    End With
End Sub

验证每个 Name 是一个单元块。