2017-06-20 122 views
0

我有以下代码。它从一个工作簿复制工作表到另一个工作簿。如果两个文件都关闭,它工作正常。我想修改这段代码,首先检查两个文件是否都打开,关闭它们而不保存任何更改,最后执行与我现在相同的操作。用VB Scritp如何检查一个excel文件是否已经打开并关闭它而不保存它。

' Create Excel object 
Set objExcel = CreateObject("Excel.Application") 

' Open the source workbook 
Set SOURCE = objExcel.Workbooks.Open("Path\Source.xls") 


' Open the destination workbook 
Set DEST = objExcel.Workbooks.Open("C:Path\Destination.xlsx") 


objExcel.Visible = False 


' Select the range on source Sheet1 you want to copy 
SOURCE.Worksheets("Sheet1").Range("A1:AZ2500").Copy 

' Paste it on Destiny Sheet1, starting at A1 
DEST.Worksheets("Sheet").Range("A1").PasteSpecial 


' Save and close workbooks 

DEST.save 
DEST.close 
SOURCE.close 
+0

删除'DEST.save'和修改,最后前行'DEST.close FALSE' – Vityata

+0

柏迪,在文件被关闭的情况下,我希望他们能够保存并关闭。 –

回答

1

下面的代码将检查是否Excel是开放的,如果是,请检查您的源和目标工作簿,关闭它们不保存他们,如果他们是开放的。之后,它将打开文件,并将目标中的范围设置为Source中的范围。

鉴于代码每次都是纯粹设置相同的范围,我不禁想到只需打开Source工作簿,然后将其保存为目标并覆盖现有目标文件即可。

让我知道如果你需要任何进一步的解释这是如何工作的。

Option Explicit 

Dim oExcel, oWorkbook 

' Check if Excel is open 
On Error Resume Next 
Set oExcel = GetObject(, "Excel.Application") ' If Excel is open this will set a reference to it 
On Error Goto 0 
If Not IsObject(oExcel) Then 
    ' Excel wasn't running, create an instance 
    Set oExcel = CreateObject("Excel.Application") 
End If 

' Check any open workbooks in the Excel instance 
If oExcel.Workbooks.Count > 0 Then 
    For Each oWorkbook In oExcel.Workbooks 
     If oWorkbook.Path = "Path\Source.xls" Or oWorkbook.Path = "Path\Destination.xlsx" Then 
      oWorkbook.Close True ' closes workbook without saving changes 
     End If 
    Next 
End If 

' Open the source workbook 
Set SOURCE = oExcel.Workbooks.Open("Path\Source.xls") 

' Open the destination workbook 
Set DEST = oExcel.Workbooks.Open("Path\Destination.xlsx") 

oExcel.Visible = False 

' Set the destination range to the source range 
DEST.Worksheets("Sheet").Range("A1:AZ2500") = SOURCE.Worksheets("Sheet1").Range("A1:AZ2500") 

' Save and close workbooks 
DEST.Save 
DEST.Close 
SOURCE.Close 

Set oExcel = Nothing ' drop the reference to excel object 
+0

嗨戴夫,感谢您的帮助。该代码没有工作,至少作为VB脚本。显示“未定义变量”(用于源)。 –

+0

嗨,何塞,这将是因为我在代码的开头添加了“Option Explicit”。它使变量声明是强制性的,对于确保你跟踪你正在使用的内容很有用。您需要在代码中添加Dim SOURCE和Dim DEST语句来声明它们,然后解决未定义的变量问题。 – Dave

相关问题