As seen, Row 1 is the column headers (ITEM, PART NUMBER, ATA 2 ..) Using VBA, How do I find the corresponding column in which a specific header is present (In Row 1)?
Example:
ITEM. is in Column A, so it should return 'A'
MTBR is in Column L, so it should return 'L'
The intent of this is to automate copy of particular columns from one spreadsheet to another. The current code is:
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
As seen above, I am manually giving the column name. I want that the particular column is found after matching the text in Form.ComboBox2.Value
in wb.Worksheets(cmb)
How do I search for the string in Form.ComboBox2.Value
in Row 1 of wb.Worksheets(cmb)
and return its column number that I can plug here Set sourceColumn = wb.Worksheets(cmb).Columns("B")
Untested but should get you started:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.