如何在Excel Excel中基于标题从一个工作簿复制到另一个工作簿

时间:2016-11-02 12:22:18

标签: excel-vba vba excel

Sub copycolumns()

Dim y As Workbook
Dim x As Workbook
Dim ws As Worksheet
Dim sh As Worksheet

Set x = Workbooks.Open("C:\Users\hshabbir\Desktop\testing.xlsx")
Set sh = x.Sheets("Sheet2")

Set y = ThisWorkbook
Set ws = y.Sheets("Sheet1")
Application.ScreenUpdating = 0

Dim i As Integer, searchedcolumn As Integer, searchheader As Object

For i = 1 To 8    
    Set searchheader = ws.Cells(1, i)    
    searchedcolumn = 0

    On Error Resume Next
    searchedcolumn = sh.Rows(1).Find(what:=searchheader.Value, lookat:=xlWhole).Column
    On Error GoTo 0

    If searchedcolumn <> 0 Then
        ws.Columns(searchedcolumn).Copy Destination:=searchheader     
    End If
Next i

x.Close

End Sub

1 个答案:

答案 0 :(得分:0)

当我使用以下程序与工作簿,它工作正常并将日期从一张纸复制到另一张。 子copycolumns1()

Dim i As Integer,searchcolumn As Integer,searchheader As Object

设置searchheader = Sheets(2).Cells(1,1)

searchingcolumn = 0 On Error Resume Next  searchingcolumn = Sheets(1).Rows(1).Find(what:= searchheader.Value,lookat:= xlWhole).Column  错误转到0

如果searchcolumn&lt;&gt; 0然后   表格(1)。列(搜索列)。复制目的地:=搜索头  结束如果

End Sub

但是我没有让它从一个工作簿转移到另一个工作簿