If / Else检查整行的标题顺序

时间:2017-02-02 18:27:46

标签: vba excel-vba if-statement excel

我尝试运行if / else测试,该测试将查看一行列标题,如果标题行与标题名称的特定顺序不匹配,则抛出错误/停止子。

我有一个非常基本的代码放在一起进行初步测试,但是,它正在查看每个单独的列标题名称,以便我获得一长串消息框通知。

我知道有一种方法可以让宏观看整个行作为一个整体,并根据行是否匹配继续或停止。我只是无法弄清楚我的代码中的操作方式/操作方式。这个很新。任何帮助将不胜感激!

Sub testheaders()

Dim arrCols, x As Long, sht As Worksheet, f As Range, s

'All the fields in the final version in specific order needed
arrCols = Array("Plan Number", "Plan Name", "Division Basis    ", "Division Value    ", "Division Name    ", "SSN", "SSN Ext", "Participant Name", "Hire Date", "Term Date", "LOA Reason", ...........)

Set sht = ActiveSheet


For Each Row In arrCols
    Set f = sht.Rows(1).Find(What:=s, LookIn:=xlValues, lookat:=xlWhole)
    If Not f Is Nothing Then
        'header found
        MsgBox "header found"

    Else
        'not found
        MsgBox "missing header"

    End If

Next s

End Sub

1 个答案:

答案 0 :(得分:0)

尝试下面的代码,我采用了不同的方法,使用Application.Match函数。

(如果需要,可以删除MsgBox

Sub testheaders()

Dim arrCols, sht As Worksheet, s
Dim LastCol As Long, HeaderRng As Range


'All the fields in the final version in specific order needed
arrCols = Array("Plan Number", "Plan Name", "Division Basis    ", "Division Value    ", "Division Name    ", "SSN", "SSN Ext", "Participant Name", "Hire Date", "Term Date", "LOA Reason")

Set sht = ActiveSheet

With sht
    ' find last column with data in the first row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    ' set the scanned range with data in the Header row
    Set HeaderRng = .Range(.Cells(1, 1), .Cells(1, LastCol))

    For Each s In arrCols
        If IsError(Application.Match(s, HeaderRng, 0)) Then '<-- no Match
            MsgBox s & " is a missing header"
        Else '<-- successful match
            MsgBox s & " header found"
        End If        
    Next s
End With

End Sub