2017-07-03 98 views
1

我試圖做一個宏,讓我直接放棄這一非常常用的工作表到我們需要的文件。這是這是一種常用的工作表,我希望能夠快速輕鬆地插入現有文檔以便經常複製和使用。複製啓用宏的工作表從一個工作簿到另一個「運行時錯誤‘1004’」

我收到:運行時錯誤「1004」:Excel不能訪問「垃圾」。該文件可能是隻讀或加密的。

該代碼是從在堆棧溢出另一溶液改性,以便被上祝任何文件全球使用。 (這是最終的目標在這裏)代碼如下:

Sub foo() 
Dim x As Workbook 
Dim y As Workbook 
Dim z As String 
z = ActiveWorkbook.Path 

Dim WS As Worksheet 
Sheets.Add.Name = "Finance" 

'## Open both workbooks first: 
Set x = Workbooks.Open("Desired worksheet file path") 
Set y = Workbooks.Open(z) 

'Now, copy what you want from x: 
x.Sheets("Finance1").Range("A1:G12").Copy 

'Now, paste to y worksheet: 
y.Sheets("Finance").Range("A1:G12").PasteSpecial 

'Close x: 
x.Close 

End Sub 

在錯誤點兩份文件都是開放的。

回答

1

ActiveWorkbook.Path給出了activeworkbook的路徑,你應該添加文件給它。就像這樣:

Set y = Workbooks.Open(z & "\fileSample.xlsx")

有一個錯誤一個進一步的選項 - 如果不保存ActiveWorkbook,那就不是返回任何東西。因此,檢查它是這樣的: If len(activeworkbook.path)>0 then

+0

將這項工作自動化目的:Z = ActiveWorkbook.Path& 「\」 –

+0

N = ActiveWorkbook.Name –

+0

集合Y = Workbooks.Open(Z&N) –

1

Thec代碼將是這樣的。

Sub foo() 
    Dim x As Workbook 
    Dim y As Workbook 
    Dim z As String, FileName1 As String, FileName2 As String 

    z = ThisWorkbook.Path & "\" 

    Dim WS As Worksheet 
    FileName1 = "test1.xlsx" 
    FileName1 = "test2.xlsx" 
    '## Open both workbooks first: 
    Set x = Workbooks.Open(z & FileName1) 
    Set y = Workbooks.Open(z & FileName2) 

    'Now, copy what you want from x: 
    x.Sheets("Finance1").Range("A1:G12").Copy y.Sheets("Finance").Range("A1") 

    x.Close 

End Sub 
+0

這會是好爲我的代碼? Z = ActiveWorkbook.Path& 「\」 N = ActiveWorkbook.Name 昏暗WS作爲工作表 Sheets.Add.Name = 「財經」 「##打開這兩個工作簿第一: 集X = Workbooks.Open (「\\\\ tehis6803 \ Wafer_Processing \ Excel Macro,VBA&Immobile Documents \ reference \ Wafer Cost Analysis January2016.xlsm」) Set y = Workbooks.Open(z&n) '現在,複製你想要的x: x.Sheets(「Finance1」)。Range(「A1:G12」)。複製 '現在,粘貼到y工作表: y.Sheets(「Finance」)。Range(「A1:G12」) .PasteSpecial –

+0

Tha t沒有那麼好。我基本上加入這樣的:(Z = ActiveWorkbook.Path& 「\」 N = ActiveWorkbook.Name) –

+0

除了:設置Y = Workbooks.Open(Z&N) –

相關問題