2017-04-10 83 views
0

我有這個基於工作的項目,VBA會自動將選擇列複製到不同工作簿中的某些工作表。VBA將Excel列複製到不同的工作簿並關閉文件

Sub Macro2() 
MsgBox "It's working 2" 


Dim incidentDataColumnC As Range, SpecificDataColumnA As Range 

Set incidentDataColumnC = Workbooks("01 - January 2017 Incident Data.csv").Worksheets(1).Columns("C") 
Set SpecificDataColumnA = Workbooks.Open("Z:\****\Real Test\01 - January 2017 Service Desk Reports.xlsx").Worksheets(3).Columns("A") 

incidentDataColumnC.Copy Destination:=SpecificDataColumnA 
SpecificDataColumnA.Parent.Close 

Dim incidentDataColumnE As Range, SpecificDataColumnB As Range 

Set incidentDataColumnE = Workbooks("01 - January 2017 Incident Data.csv").Worksheets(1).Columns("E") 
Set SpecificDataColumnB = Workbooks.Open("Z:\****\Real Test\01 - January 2017 Service Desk Reports.xlsx").Worksheets(3).Columns("B") 


incidentDataColumnE.Copy Destination:=SpecificDataColumnB 
SpecificDataColumnB.Close 

Dim incidentDataColumnH As Range, SpecificDataColumnC As Range 

Set incidentDataColumnH = Workbooks("01 - January 2017 Incident Data.csv").Worksheets(1).Columns("H") 
Set SpecificDataColumnC = Workbooks.Open("Z:\****\Real Test\01 - January 2017 Service Desk Reports.xlsx").Worksheets(3).Columns("C") 

incidentDataColumnH.Copy Destination:=SpecificDataColumnC 
SpecificDataColumnC.Close 
.... 
.... 
MsgBox "It ran" 
End Sub 

該代碼的功能應該是通過複製列的方式,但它返回一個錯誤,說明目標文件已打開。

我想找到解決此錯誤的方法,並且如果可能在複製過程運行後關閉每個文件。

我嘗試了一個簡單的.Close命令,但彈出一個錯誤,說它不受支持。

+1

簡單的答案是打開工作簿一次,而不是三次。 – YowE3K

+0

請聲明一些對象變量並回復給我們:https://msdn.microsoft.com/en-us/library/office/gg251791.aspx – Absinthe

+1

'SpecificDataColumnC'是'Range',你不能'SpecificDataColumnC .Close',同上'SpecificDataColumnB'。另外,請參閱上文。 –

回答

2

您應該使用Workbook對象來跟蹤您的工作簿。您也可以通過直接複製範圍來簡化代碼,而不是將對象分配給每個範圍。

Sub Macro2() 
    Dim wb1 As Workbook 
    Dim wb2 As Workbook 
    MsgBox "It's working 2" 

    Set wb1 = Workbooks("01 - January 2017 Incident Data.csv") 
    Set wb2 = Workbooks.Open("Z:\****\Real Test\01 - January 2017 Service Desk Reports.xlsx") 

    wb1.Worksheets(1).Columns("C").Copy wb2.Worksheets(3).Columns("A") 
    wb1.Worksheets(1).Columns("E").Copy wb2.Worksheets(3).Columns("B") 
    wb1.Worksheets(1).Columns("H").Copy wb2.Worksheets(3).Columns("C") 
    '.... 
    '.... 
    wb2.Close 
    MsgBox "It ran" 
End Sub 
+0

這工作,但它顯示提示保存更改,有沒有辦法讓它保存更改,從而導致提示不顯示? –

+1

@DylanF - 是的,'Close'方法有一個參數來指定是否保存更改。所以你可以說,例如,'wb2.Close SaveChanges:= True'。 (我沒有包括這個,因爲你沒有將它包含在你的問題的代碼中,所以我假設你想讓用戶選擇是否保存更改。) – YowE3K

+0

實際上它根本沒有複製,是嗎?我從你的解決方案中失去了一個步驟? –

相關問題