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

时间:2016-04-08 09:41:18

标签: excel vba excel-vba worksheet-function

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

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

1 个答案:

答案 0 :(得分:2)

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

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 的形式。