保存当前打开的所有excel工作簿并在以后打开
我目前面临着一个我想要的问题:
1.将所有当前打开的Excel工作簿存储在一个数组中
2.保存并closures工作簿
打开所有打开的工作簿
4.重新回到一个特定的工作簿
目前的代码我有:
For Each wb In Application.Workbooks wb.Save Next wb
按预期工作,但我不同的Excel工作簿保持“闪动”,这是一种有点刺激,因此需要保存和closures所有。
我明白,要重新回到一个特定的工作簿,你可以使用激活function。 如果我在“For each loop”中设置了一个数组,它将不会工作,因为它将成为循环的双精度值。
因为我是VBA的新手,我真的很感谢你们所有的意见。
谢谢!
我在这段代码中给了你两个不同的选项。 使用集合或数组。 您可以使用Collection循环中的For Each 项逐步完成集合,而数组需要一个For..Next循环。
Sub All_OpenWorkBooks_Collection() Dim wrkBk As Workbook '''''''''''''''''''''''''''''''''''''''''''''''''''''' 'Add to a collection ' '''''''''''''''''''''''''''''''''''''''''''''''''''''' Dim vItem As Variant Dim colWorkBooks As Collection Set colWorkBooks = New Collection For Each wrkBk In Workbooks If wrkBk.Name <> ThisWorkbook.Name Then colWorkBooks.Add wrkBk.FullName wrkBk.Close SaveChanges:=True End If Next wrkBk Set wrkBk = Nothing For Each vItem In colWorkBooks Workbooks.Open (vItem) Next vItem '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 'Set a reference to a specific workbook - can then use wrkBk to refer to it. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Set wrkBk = Workbooks("Copy (4) of New Microsoft Excel Worksheet.xlsx") wrkBk.Activate End Sub '------------------------------------------------------------------------ Sub All_OpenWorkbooks_Array() Dim wrkBk As Workbook '''''''''''''''''''''''''''''''''''''''''''''''''''''''' 'Add to an array. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''' Dim x As Long Dim arrWrkBk() As Variant ReDim arrWrkBk(1 To Workbooks.Count) For x = Workbooks.Count To 1 Step -1 If Workbooks(x).Name <> ThisWorkbook.Name Then arrWrkBk(x) = Workbooks(x).FullName Workbooks(x).Close SaveChanges:=True End If Next x For x = 1 To UBound(arrWrkBk) If arrWrkBk(x) <> "" Then Workbooks.Open (arrWrkBk(x)) End If Next x '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 'Set a reference to a specific workbook - can then use wrkBk to refer to it. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Set wrkBk = Workbooks("Copy (4) of New Microsoft Excel Worksheet.xlsx") wrkBk.Activate End Sub
编辑:注意我退后一步通过数组循环 – 因为它正在计算打开的工作簿,并closures它们打开工作簿的数量随着循环的进展而下降(所以当它到了循环数4时,很有可能工作簿数字4已经closures)。
编辑2:对工作空间的评论可能正是你以后 – 我会先检查出来。
在你的循环帮助之前添加.ScreenUpdating = False?
和.ScreenUpdating = true后重新打开。