2017-03-07 35 views
1

我想在表中找到具有特定標題的列,其中幾乎所有標題都被合併。這裏是什麼我的表看起來像虛擬數據爲例:查找具有合併單元格的列號vba

Table with headers merged

我試圖要麼尋找行1和2(範圍A1:XFD1A2:XFD2),但似乎VBA找不到列我正在尋找:

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 

謝謝。

回答

1

你只需要改變你的

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

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

既然你正在尋找2行確實

1

你可以嘗試這樣的:

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 

我還沒有測試過D它,但它應該工作... :) 幾乎你只是循環你的範圍,並檢查每一列是否合併。然後你給MsgBox。通過您的專欄

0

只是循環和排

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 
0

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 
1

因爲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