将字段名称存储在 excel-vba 中的数组中

Storing The field names in an array in excel-vba

我在一个工作表中有 10 列,每个工作表都有一个在名称框中定义的指定 ID。如何使用 VBA 将 ID 存储在数组中。

p.s。我不想存储列标题。我想存储他们的 ID,这些 ID 在每一列的名称框中定义。

遍历工作簿的命名范围;检查每个名称是否指的是该工作表上的一个范围,以及命名范围是否指的是至少部分位于第一行的范围。

Dim n As Long, vColNames As Variant
Dim c As Long, twb As Workbook

Set twb = ThisWorkbook

With Worksheets("Sheet1")
    With .Cells(1, 1).CurrentRegion
        'dim the array one-based to parallel the columns
        ReDim vColNames(1 To .Columns.Count)

        'loop through all names looking for ones that intersect first row
        For n = 1 To twb.Names.Count
            'check the parent worksheet first
            If twb.Names(n).RefersToRange.Parent.Name = .Parent.Name Then
                ' next check to ensure first row is part of named range
                If Not Intersect(twb.Names(n).RefersToRange, .Rows(1), .Cells) Is Nothing Then
                    vColNames(Intersect(twb.Names(n).RefersToRange, .Rows(1)).Cells(1, 1).Column) = _
                        twb.Names(n).Name
                End If
            End If
        Next n
    End With
End With


For c = LBound(vColNames) To UBound(vColNames)
    Debug.Print vColNames(c)
Next c

具有工作簿范围的名称将显示为 myNamedRange;具有工作表范围的将采用 Sheet1!myNamedRange.

的形式