循环遍历列以获取基于标题的列号

时间:2017-11-10 08:20:42

标签: excel vba excel-vba

我有一个模板,其中包含一组列(170)和标题标题(第1行单元名称)。这总是相同的,直到用户在其间添加列(他们被指示不更改标题)。我们的想法是在涉及添加色谱柱时使其防篡改。

我想创建变量来保存一些标题(具有容纳所有标题的容量)并使用模板检查这些变量以找出列号(在我认为的循环中)。使函数调用它可能是最明智的吗?

Dim ColHeader1Str as string 'literal row 1, column 1 value (which is always 
'the same string and position in the template)
Dim iColHeader1 as integer 'holds the (to be set) value of the column number

Set ColHeader1Str = "ColHeader1"

现在我想要一个循环,它循环遍历所有列(最后一列= 200)并检查列号与ColHeader1Str匹配的内容并将其存储在iColHeader1

类似于:

Function find_columnNmbr
  Dim i As Integer
    For i = 1 To 200 Step 1
     If 'ColHeader1Str matches actual column header name
        'set found integer as iColHeader1 and so forth
        Exit For
     End If
    Next
End Function`

我知道我错过了几步,我希望你们能帮助我。

更新:模板已设置列标题。当用户与其进行交互时,结果可能是列移位,或者他们添加更多。我有一个工作簿需要从用户更改的模板中加载数据。

即。模板有第1,2,3,4列,名称为column1,第2列等。用户广告一个随机列,所以现在有5.循环需要遍历列标题的名称并标识列号原始模板列1,2等基于具有原始名称的字符串变量,我事先已经硬编码。这些是公共常量。

2 个答案:

答案 0 :(得分:1)

函数LookForHeaders做什么:输入一个字符串,然后在usersheet.range(1:1)中搜索字符串。如果找到,则返回该单元格的列号,否则返回0.

Private Function LookForHeaders(ByVal headerName As String) As Long
    Dim rng As Range
    Dim userSheet As WorkSheet
    Set userSheet = 'userSheet here'

    On Error GoTo NotFound
    LookForHeaders = userSheet.Range("1:1").Find(headerName).Column
    Exit Function
NotFound:
    LookForHeaders = 0
End Function

Private Sub Test()
    Dim rng As Range
    Dim template As WorkSheet
    Set template = 'template here'
    For Each rng In template.Range(Cells(1,1), Cells(1,200))
        iColHeader1 = LookForHeaders(rng.Value)
        'Do something with iColHeader1
    Next rng
End Sub

答案 1 :(得分:0)

不确定您要查找的内容,但此处为示例

Option Explicit
Public Sub Example()
    Dim LastCol As Long
    Dim i As Long

    LastCol = ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count).Column

    For i = 1 To LastCol
        If Cells(i) = "Name" Then
            Debug.Print Cells(i).Address
        End If
    Next
End Sub