在工作表 2 的 50 个标题下,每行都有未知数量的数据。
我总是更喜欢公式而不是 vba,但是如果你有 unknown 行数和 50 标题,那么我个人将永远不会选择公式。特别是如果我不得不把它拖下来。这是一个 VBA 解决方案。
假设您的 Sheet2 看起来像这样
将此粘贴到Sheet1 工作表代码区域。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
If Target.Cells.CountLarge > 1 Then Exit Sub
Dim wsI As Worksheet, wsO As Worksheet
Dim lRow As Long, nCol As Long
Dim sSrch As String
Dim aCell As Range, rng As Range
Set wsI = ThisWorkbook.Sheets("Sheet2")
Set wsO = ThisWorkbook.Sheets("Sheet1")
Application.EnableEvents = False
If Not Intersect(Target, Range("A1:C1")) Is Nothing Then
sSrch = Cells(1, Target.Column).Value
Set aCell = wsI.Rows(1).Find(What:=sSrch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
nCol = aCell.Column
lRow = wsI.Cells(wsI.Rows.Count, nCol).End(xlUp).Row
Set rng = wsI.Range(wsI.Cells(2, nCol), wsI.Cells(lRow, nCol))
End If
If Not rng Is Nothing Then
Range(Cells(2, Target.Column), Cells(Rows.Count, Target.Column)).ClearContents
rng.Copy Cells(2, Target.Column)
End If
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
输出