Excel - VBA切换工作簿

时间:2017-06-16 08:25:25

标签: excel vba

我有3本工作簿

来源工作簿

目标工作簿

参考工作簿 - (包含所有工作簿中可见的宏)

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

  • 激活似乎没有帮助我,如果这是一个错误或它是什么,我不会。我已经在这一步停了很长一段时间了。

  • 此工作簿功能将我带回参考工作簿。

希望我的问题很明确。感谢您的帮助。

' 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 = Thisworkbook我的引用被更改为源代码到工作簿,这不是我想要的工作簿,因为它包含许多其他活动的宏。希望这是代码很好。

1 个答案:

答案 0 :(得分:1)

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

示例:

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