Vba If/Else检查整行的标题顺序
我正在尝试运行一个if/else测试,该测试将查看一行列标题,如果标题行与标题名的特定顺序不匹配,则抛出一个error/stop sub 我有一个用于初始测试的非常基本的代码,它正在工作,但是,它正在查看每个单独的列标题名称,因此我得到了一个消息框通知的长列表 我知道有一种方法可以让宏将整行视为一个整体,根据行是否匹配继续或停止。我就是不知道如何/在我的代码中操作什么。这一点很新。任何帮助都将不胜感激Vba If/Else检查整行的标题顺序,vba,excel,if-statement,Vba,Excel,If Statement,我正在尝试运行一个if/else测试,该测试将查看一行列标题,如果标题行与标题名的特定顺序不匹配,则抛出一个error/stop sub 我有一个用于初始测试的非常基本的代码,它正在工作,但是,它正在查看每个单独的列标题名称,因此我得到了一个消息框通知的长列表 我知道有一种方法可以让宏将整行视为一个整体,根据行是否匹配继续或停止。我就是不知道如何/在我的代码中操作什么。这一点很新。任何帮助都将不胜感激 Sub testheaders() Dim arrCols, x As Long, sht
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
尝试下面的代码,我使用了另一种方法,使用
应用程序.Match
函数
(如果需要,可以删除MsgBox
)
子测试头()
尺寸arrCols,短如工作表,s
调暗与长度相同,头部与射程相同
'最终版本中的所有字段需要按特定顺序排列
arrCols=数组(“计划编号”、“计划名称”、“部门依据”、“部门价值”、“部门名称”、“SSN”、“SSN Ext”、“参与者名称”、“雇用日期”、“期限日期”、“LOA原因”)
设置sht=ActiveSheet
用短发
'查找第一行中包含数据的最后一列
LastCol=.Cells(1,.Columns.Count).End(xlToLeft).Column
'使用标题行中的数据设置扫描范围
设置头错误=.Range(.Cells(1,1),.Cells(1,LastCol))
对于每一个arrCols
如果IsError(应用程序匹配(s,Head Rebug,0))然后“如果你不想看到一个消息框,那么考虑删除产生它的语句。如果希望宏在标头不存在的情况下Stop
,则插入Stop
语句If f为nothing
。我想让那些盒子弹出测试是一个问题,而不是帮助!如果工作表包含一个ListObject
(也称为“格式化为表的范围”),则有一种更简洁的方法来获取其标题行。是吗?我没有遵循你的代码,你在arrCols中的每一行都有,但是用下一个s
关闭它,然后在你的中找到你有什么:=s
。是否要在第1行中查找数组中的每个值?与其使用MsgBox
,不如只使用debug.print
函数,这样会更干净。这样你就不会被弹出窗口轰炸。
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