2017-06-20 123 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

相關問題