Excel – VBA切换工作簿

我有3个工作簿

工作簿

目标工作簿

参考工作簿 – (包含所有工作簿中可见的macros)

是否可以更改活动工作簿( 目标工作簿)和(作为活动工作簿的工作簿)之间的切换。

  • 激活似乎没有帮助我,我不,如果这是一个错误或是什么。 现在我已经停止了这一步。

  • 此工作簿function带我回到参考工作簿。

希望我的问题很清楚。 感谢你的帮助。

' My code is in a test macroworkbook ' I am having a workbook opened 1.xlsx ' Opening a workbook countrypricelist.xls 'running the code from Dim sourcewb As Workbook Dim targetWorkbook As Workbook Dim filter As String Dim filter2 As String Dim rw As Long Dim x As Range Dim y As Range Set sourcewb = ActiveWorkbook Set x = sourcewb.Worksheets(1).Range("A:F") Dim sourceSheet As Worksheet Set sourceSheet = sourcewb.Worksheets(1) MsgBox sourceSheet.Name x.Select MsgBox sourceSheet.Name x.Select MsgBox sourcewb.Name ' This gives me sourceworkbook name. filter = "(*.xls),*.xls" Caption = "Please Select an input file " Application.ScreenUpdating = False Filename = Application.GetOpenFilename(filter, , Caption) Set targetWorkbook = Application.Workbooks.Open(Filename) Set y = targetWorkbook.Worksheets(1).Range("A:F") y.Select Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) MsgBox targetSheet.Name Set targetWorkbook = ActiveWorkbook MsgBox targetWorkbook.Name 'This gives me target workbook name y.Select sourcewb.Activate MsgBox sourcewb.Name ' Source workbook becomes same as targeworkbook. x.Select MsgBox sourcewb.Name & " This is the source workbook " MsgBox targetWorkbook.Name & " This is the target workbook " With sourcewb.Worksheets(1) For rw = 2 To Cells(Rows.Count, 1).End(xlUp).Row Cells(rw, 3) = Application.VLookup(Cells(rw, 2).Value2, x, 3, False) Cells(rw, 4) = Application.VLookup(Cells(rw, 2).Value2, x, 4, False) Cells(rw, 5) = Application.VLookup(Cells(rw, 2).Value2, x, 5, False) Next rw End With MsgBox "All required columns from source mapped to target file " MsgBox "Trying to map from target to source " Set sourcewb = ActiveWorkbook MsgBox ActiveWorkbook.Name Application.ScreenUpdating = False 

所以,如果我改变了这一行sourcewb =这个工作簿,我的参考被更改为工作簿的源代码,这不是我想要的工作簿,因为它包含许多其他活动的macros。 希望这是代码是好的。

Excel工作簿对象允许您以编程方式打开,编辑和closures任何工作簿,而不仅仅是当前“已激活”的工作簿。

例:

 Dim wb as Excel.Workbook, otherwb as Excel.Workbook Dim ws as Excel.Worksheet, otherws as Excel.Worksheet Set wb = Workbooks.Open "somefile.xlsx" Set otherwb = Workbooks.Open "otherfile.xlsx" Set ws = wb.Sheets(1) Set otherws = otherwb.Sheets(1) ' do stuff ws.Cells(1,1) = otherws.Cells(1,1) 'save changes wb.Save