2017-03-13 59 views
0

我有以下這段代碼的問題從多個文件粘貼。 當我打開excel時,它不會運行。Excel的VBA,

它不會從我的文件正確粘貼。我希望它進入最後一行並粘貼我的信息,然後從第二個文件中退出並粘貼,等等。

有什麼想法?

Private Sub Workbook_Open() 
Dim FolderPath As String 
Dim FileName As String 

FolderPath = "D:\excelprojekt\" 
FileName = Dir(FolderPath & "*.xlsx") 

Dim lastrow As Long 
Dim lastcolumn As Long 

Do While FileName <> "" 
Workbooks.Open (FolderPath & FileName) 

lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row 
lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column 
Range(Cells(1, 1), Cells(lastrow, lastcolumn)).Copy 
Application.DisplayAlerts = False 
ActiveWorkbook.Close 


With ActiveSheet 
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 
ActiveCell.Offset(rowOffset:=2, columnOffset:=0).Activate 
ActiveSheet.PasteSpecial 
End With 

FileName = Dir 
Loop 

End Sub 
+0

你可能會在這裏找到至少一個答案:http://stackoverflow.com/questions/11369762/workbook-open-sub-wont-run-when-i-open-the-workbook – Ralph

回答

1

我認爲可以在關閉工作簿後保留複製數據,但這裏沒有理由這樣做。如果您符合工作簿引用的條件,則可以在兩者都打開時從一個工作簿複製到另一個工作簿。如果你知道你想從進入複製什麼表,你應該明確地引用他們,而不是使用ActiveSheet爲好(我認爲ActiveSheet將是什麼板材是活躍在文件最後一次打開文件時保存)

Private Sub Workbook_Open() 
Dim FolderPath As String 
Dim FileName As String 

FolderPath = "D:\excelprojekt\" 
FileName = Dir(FolderPath & "*.xlsx") 

Dim lastrow As Long 
Dim lastcolumn As Long 

Dim wbOpened as Workbook 

Do While FileName <> "" 
Set wbOpened = Workbooks.Open(FolderPath & FileName) 
With wbOpened.ActiveSheet 
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row 
lastcolumn = .Cells(1, Columns.Count).End(xlToLeft).Column 
.Range(.Cells(1, 1), .Cells(lastrow, lastcolumn)).Copy 
End With 

ThisWorkbook.ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2).PasteSpecial 

Application.DisplayAlerts = False 
wbOpened.Close 

FileName = Dir 
Loop 

End Sub