|
楼主 |
发表于 2024-8-6 08:39
|
显示全部楼层
Sub FUZHI()
Dim sourceSheet As Worksheet, ruleSheet As Worksheet, destSheet As Worksheet
Dim sourceLastRow As Long, destLastRow As Long, rulelastrow As Long, i As Long, j As Long
Dim sourceColIdx As Long, destColIdx As Long
' 设置工作表对象
Set sourceSheet = ThisWorkbook.Sheets("源数据")
Set ruleSheet = ThisWorkbook.Sheets("规则")
Set destSheet = ThisWorkbook.Sheets("销售")
' 获取源数据表的最后一个数据行
sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
' 获取目标数据表的最后一行有数据的单元格
destLastRow = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row + 1
rulelastrow = ruleSheet.Cells(ruleSheet.Rows.Count, "A").End(xlUp).Row
' 遍历规则表的A列
For i = 1 To rulelastrow
' 查找列标题在源数据表中的位置
sourceColIdx = Application.Match(ruleSheet.Cells(i, 1).Value, sourceSheet.Rows(1), 0)
If IsNumeric(sourceColIdx) Then
' 确定目标列的列号
destColIdx = i
' 确保目标列的起始单元格是空的,避免覆盖数据
While destSheet.Cells(destLastRow, destColIdx).Value <> ""
destLastRow = destLastRow + 1
Wend
' 复制数据并粘贴到目标数据表
sourceSheet.Range("A2:A" & sourceLastRow).Columns(sourceColIdx).Copy
destSheet.Cells(destLastRow, destColIdx).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Else
' 如果没有找到列标题,则输出错误信息
Debug.Print "未找到列标题: " & ruleSheet.Cells(i, 1).Value
End If
Next i
MsgBox "数据复制完成。"
End Sub
|
|