在工作簿之间自动应对列

时间:2016-02-03 12:59:24

标签: excel vba excel-vba

我需要帮助创建一段代码。

  • 确定两个单独的工作簿:workbook1(源文件)& workbook2(active.workbook)。
  • 获取workbook1中的列标题,在工作簿2中找到该列标题,并将该列的内容从workbook1复制到工作簿2中。
  • 移至workbook1中的下一列,直到其标题为空。

1 个答案:

答案 0 :(得分:1)

此代码适用于我。请注意评论。

Sub copyA2B()
Dim wb As Workbook
Dim wbSrc As String
Dim cel As Range
'assuming you don't know the source workbook name, looping through the workbooks, otherwise no loop needed
For Each wb In Workbooks
    If wb.Name <> ActiveWorkbook.Name Then
        wbSrc = wb.Name
        Exit For
    End If
Next
With Workbooks(wbSrc).ActiveSheet
    'assuming the column order is different between the two files, looping through the titles, otherwise no loop needed
    For Each cel In .Rows(1).Cells 'assuming the titles are in the first row in both workbooks
        If cel <> "" And cel(2) <> "" Then
            .Range(cel(2), cel(1).End(xlDown)).Copy Rows(1).Find(cel.Value)(2)
        End If
    Next
End With

End Sub