嗨我一直在为以下代码的for循环中的行获取“变量或未设置块变量”。谁能告诉我哪里出错了?感谢
Public Sub TestFind()
Set wsNew = Worksheets.Add(after:=Worksheets(Worksheets.Count))
wsNew.Range(wsNew.Cells(1, 1), wsNew.Cells(1, 17)).Value _
= Array("ReturnId", "GridName", "Item", "TabName", "AltFldName", "FieldPos", "Reference", "Type", _
"SortPos", "FieldSize", "CalcField", "CellDesc", "DoNotExport", "SortStrategy", "Threshold", "IsInnerGridCell", "ReportLine")
Dim Nm As Name
Dim rng As Range
Dim wb As Workbook
Set wb = ThisWorkbook
For Each Nm In ThisWorkbook.Names
rng = Nm.RefersToRange.Value
Next
End Sub
答案 0 :(得分:3)
代码中有两个问题:
1-并非所有名称都必须指向命名范围。例如,它们可能指的是常量。因此,在假设名称真正涉及范围之前,您需要添加一些检查。
2-将范围对象分配给命名范围,您需要使用Set
试试这个:
Dim Nm As Name, rng As Range
For Each Nm In ThisWorkbook.Names
Debug.Print Nm.Name
On Error Resume Next
Set rng = Nm.RefersToRange ' <-- Use Set to assign object references
If Err.Number <> 0 Then GoTo NextNm ' <-- This name does not refer to a named range
On Error GoTo 0
Debug.Print rng.Address
' ... Do whatever you want with the named range
NextNm:
On Error GoTo 0
Next Nm
答案 1 :(得分:1)
进行了调整和评论。
Option Explicit
Sub wqewtr()
Dim Nm As Name
Dim rng As Range
Dim var As Variant '<~~ for numbers, dates and/or text
Dim wb As Workbook
Set wb = ThisWorkbook
For Each Nm In ThisWorkbook.Names
Debug.Print Nm.Name
'nm could a 'special internal name' that starts with an underscore
'skip over these
If Left(Nm.Name, 1) <> "_" Then
'show the address of the defined name range - could be more than one cell
Debug.Print Nm.RefersToRange.Address
'do not try to assign value to a range object unless that range already has been asinged a cell or cells
'rng = Nm.RefersToRange.Value
'Debug.Print rng
'this fails if Nm is more than a single cell
'var = Nm.RefersToRange.Value
'Debug.Print var
'this guarantees one cell
var = Nm.RefersToRange.Cells(1, 1).Value
Debug.Print var
End If
Next
End Sub
答案 2 :(得分:0)
尝试以下并报告回来。你没有包括我假设的一些编码......
Dim Nm As Name
Dim rng As Range
Dim wb As Workbook
Set wb = ThisWorkbook
For Each Nm In ThisWorkbook.Names
rng = Nm.RefersToRange.Value
Next