假设工作表名称为Sheet1 和Sheet2,这将完成。
Sub colLookup()
Dim ShtOne As Worksheet, ShtTwo As Worksheet
Dim shtOneHead As range, shtTwoHead As range
Dim headerOne As range, headerTwo As range
Set ShtOne = Sheets("Sheet1")
Set ShtTwo = Sheets("Sheet2")
Dim lastCol As Long
'get all of the headers in the first sheet, assuming in row 1
lastCol = ShtOne.Cells(1, Columns.count).End(xlToLeft).column
Set shtOneHead = ShtOne.range("A1", ShtOne.Cells(1, lastCol))
'get all of the headers in second sheet, assuming in row 1
lastCol = ShtTwo.Cells(1, Columns.count).End(xlToLeft).column
Set shtTwoHead = ShtTwo.range("A1", ShtTwo.Cells(1, lastCol))
'actually loop through and find values
For Each headerTwo In shtTwoHead
For Each headerOne In shtOneHead
If headerTwo.Value = headerOne.Value Then
headerOne.Offset(1, 0).Value = headerTwo.Offset(1, 0).Value
End If
Next headerOne
Next headerTwo
End Sub
编辑:根据 cmets 中的讨论,需要一种复制和粘贴方法。这将单元格保持为下拉列表,尽管我认为下拉列表仍然无效。如果不希望这样做,可以将xlPasteAll 更改为其他格式,例如xlPasteValues。其他列在Microsoft's documentation。
Sub colLookup()
Dim ShtOne As Worksheet, ShtTwo As Worksheet
Dim shtOneHead As range, shtTwoHead As range
Dim headerOne As range, headerTwo As range
Set ShtOne = Sheets("Sheet1")
Set ShtTwo = Sheets("Sheet2")
Dim lastCol As Long
'get all of the headers in the first sheet, assuming in row 1
lastCol = ShtOne.Cells(1, Columns.count).End(xlToLeft).column
Set shtOneHead = ShtOne.range("A1", ShtOne.Cells(1, lastCol))
'get all of the headers in second sheet, assuming in row 1
lastCol = ShtTwo.Cells(1, Columns.count).End(xlToLeft).column
Set shtTwoHead = ShtTwo.range("A1", ShtTwo.Cells(1, lastCol))
'actually loop through and find values
For Each headerTwo In shtTwoHead
For Each headerOne In shtOneHead
If headerTwo.Value = headerOne.Value Then
headerTwo.Offset(1, 0).Copy
headerOne.Offset(1, 0).PasteSpecial xlPasteAll
Application.CutCopyMode = False
End If
Next headerOne
Next headerTwo
End Sub