查找具有合并单元格vba的列号

我想find一个表中具有特定标题的列,其中几乎所有标题都被合并。 这是一个虚拟数据,我的表是什么样子的例子:

表头合并

我已经试过要么在行1和2(范围A1:XFD1A2:XFD2 ),但看来, A2:XFD2无法find我要找的列:

 Sub getColumn() Dim ColNum As Integer On Error Resume Next ColNum = Workbooks(ActiveWorkbook.Name).Worksheets("Data").Range("A1:XFD1").Find(What:="Unit Cost", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False).Column MsgBox ("Column number is: " & ColNum) End Sub 

谢谢。

你只需要改变你的

 .Worksheets("Data").Range("A1:XFD1") 

 .Worksheets("Data").Range("A1:XFD2") 

因为你正在search2行

你可以试试这个:

 Option Explicit Sub getColumn() Dim ColNum As Long Dim rCell As Range Dim rRange As Range On Error Resume Next Set rRange = Workbooks(ActiveWorkbook.Name).Worksheets("Data").Range("A1:XFD1") For Each rCell In rRange If rCell.MergeArea.Cells.Count > 1 Then msgBox (rCell.Column) 'consider debug.print rCell.column End If Next rCell End Sub 

我没有testing它,但它应该工作… :)你几乎只是遍历你的范围,并检查每一列是否合并。 然后你给MsgBox。

由于Workbooks(ActiveWorkbook.Name)ActiveWorkbook相同,而后者是默认的隐式工作簿限定,因此您可以简单地编写以下帮助器函数:

 Function GetColumn(stringToFind As String) As Long On Error Resume Next GetColumn = Worksheets("Data").Rows("1:2").Find(What:=stringToFind, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False).Column End Function 

在您的“主”子目录中被利用如下:

 Sub main() Dim colNum As Long colNum = GetColumn("Unit Cost") '<--| returns 0 if "Unit Cost" is not found End Sub 

只需循环通过你的列和行

 Sub findHeader() For i = 1 To 5 If Cells(1, i).Value = "Unit Cost" Then MsgBox Cells(1, i).Value End If Next i End Sub 

Application.Match查找您的单位成本列。

 dim colm as variant with activesheet colm = application.match("unit cost", .rows(1), 0) if not iserror(colm) then debug.print colm 'column as number else colm = application.match("unit cost", .rows(2), 0) if not iserror(colm) then debug.print colm 'column as number else debug.print "not found" end if end if end if