繁体   English   中英

Excel-VBA切换工作簿

[英]Excel - VBA switching workbooks

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

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

例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM