2017-10-04 30 views
1

我excelsheet是這樣的: enter image description hereVBA - 找到一個給定的報頭/串的特定行中的&工作簿中的相應列

如所看到的,第1行是列標題(ITEM,PART NUMBER,ATA 2。 。) 使用VBA,如何找到存在特定標題的相應列(在行1中)?

例如:

ITEM。在A列,所以它應該返回「A」

MTBR是L欄,所以它應該返回「L」

這樣做的目的是從一個電子表格到另一個自動化特定列的副本。當前的代碼是:

If Form.ComboBox2.Value <> "" Then 
     Set sourceColumn = wb.Worksheets(cmb).Columns("B") 
     Set targetColumn = Workbooks("B.xlsm").ActiveSheet.Columns("A") 
     sourceColumn.Copy Destination:=targetColumn 
End If 

如上所示,我手動給列名稱。我想的是,特定列在wb.Worksheets(cmb)

Form.ComboBox2.Value文本匹配如何在wb.Worksheets(cmb)第1行中搜索字符串中Form.ComboBox2.Value並返回其列數,我可以插在此處Set sourceColumn = wb.Worksheets(cmb).Columns("B")

+0

其實,列A似乎是「*** ITEM。***」,而不是「*** ITEM ***」。你還想讓它匹配嗎? – RBarryYoung

+1

你會使用'Find()'或可能的'Match()' - 你嘗試過什麼嗎? –

+0

@RBarryYoung哦不,那麼。它應該匹配「ITEM」。 – user248884

回答

0

未測試後發現,但應該讓你開始:

Sub Tester() 

    Dim f, sht As Worksheet, hdr, sourceColumn As Range 

    Set sht = Workbooks("B.xlsm").ActiveSheet 

    If Form.ComboBox2.Value <> "" Then 

     Set sourceColumn = wb.Worksheets(cmb).Columns("B") 
     hdr = sourceColumn.Cells(1).Value 'get the source header 

     Set f = sht.Rows(1).Find(what:=hdr, lookat:=xlWhole) 

     If Not f Is Nothing Then 
      sourceColumn.Copy Destination:=f 
     Else 
      MsgBox "Destination column header '" & hdr & "' not found!" 
     End If 

    End If 

End Sub 
相關問題