我有一个包含多个工作表的excel文件,其中包含列名,值和工作表名。
我还有另一个包含列名和工作表名称的多个工作表的excel文件。
我想在不更改工作表名称的情况下将数据(列值)从一个Excel复制到另一个Excel,因为工作表名称不同,但是列名称相同。
很高兴听到一些建议。
答案 0 :(得分:1)
我的建议是在单独的模块中定义函数,但是为了简单起见,在这里我在主模块中定义了2个函数(激活工作簿和工作表)。该宏位于单独的Excel文件(Macro.xlsm)中。在同一位置包含两个Excel文件(Book1.xlsx和Book2.xlsx)。
我试图用这个例子来回答,以便可以扩展到许多工作簿和工作表中。
运行宏之前的Book2.xlsx。
运行宏后的Book2.xlsx。目的行被故意选择低了一行:-)
Option Explicit
Dim wb01 As Workbook, wb02 As Workbook
Public paTh01 As Variant, paTh02 As Variant
'/Define your functions
'Function1 openBook(paTh0, wB0)
Function openBook(path0 As Variant, wB0 As Workbook)
Set wB0 = Workbooks.Open(path0)
wB0.Activate
End Function
'Function2 openSheet(wB0, "Sheet_Name")
Function openSheet(wB0 As Workbook, sheetName0 As String)
wB0.Activate
Sheets(sheetName0).Activate
End Function
'Main Module
Sub main()
paTh01 = "D:\Book1.xlsx"
paTh02 = "D:\Book2.xlsx"
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Call openBook(paTh01, wb01)
Call openSheet(wb01, "mySheet1")
Range("A2:D4").Select
With Selection
.Orientation = 0
.Copy
End With
'If you have a loop, you should put delay otherwise excel will crash
Application.Wait (Now + TimeValue("0:00:01"))
Call openBook(paTh02, wb02)
Call openSheet(wb02, "mySheet2")
Range("A3:D5").PasteSpecial xlPasteValues, Transpose:=False
wb01.Close savechanges:=False
DoEvents
wb02.Close savechanges:=True
DoEvents
End Sub