[英]Runtime error 1004 while workbook.open method
Public Sub test()
Dim wbk As Workbook
Dim Conswbk As Workbook
Dim Temppath As String
Dim PayTemp As String
Dim Path As String
Dim lstactrow As String
Path = "C:\Users\mathew.m.1\Desktop\New folder\"
Application.DisplayAlerts = False
Set Conswbk = ThisWorkbook
Conswbk.Worksheets("Consolidate Payments").Activate
Cells.ClearContents
Cells.ClearFormats
PayTemp = Dir(Path & "*.*")
'--------------------------------------------
'OPEN EXCEL FILES
Do While PayTemp > "" 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & PayTemp)
'
Range("A12:M1000").Select
Selection.Copy
Conswbk.Worksheets("Consolidate Payments").Activate
lstactrow = Conswbk.Worksheets("Consolidate Payments").Cells(Rows.Count, "C").End(xlUp).Row
Range("B" & lstactrow).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.PasteSpecial (xlPasteAll)
Conswbk.Worksheets("Consolidate Payments").Range("A" & lstactrow).Select
Selection.Offset(1, 0).Select
ActiveCell.Value = PayTemp
wbk.Close True
Set wbk = Nothing
PayTemp = Dir
Loop
MsgBox ("Done!!!")
End Sub
First time the workbook opens. 第一次打开工作簿。 However, after the loop second time it doesn't. 但是,第二次循环后就没有。 Need help. 需要帮忙。
This will get rid of the Active*
and .select
references so you're not worried about which worksheet/workbook is which. 这将摆脱Active*
和.select
引用,因此您不必担心哪个工作表/工作簿是哪个。 Note the comment about row/col order, I can never remember off the top of my head which comes first - you may have to switch them. 请注意有关行/列顺序的注释,我永远都记不得先行了,您可能不得不切换它们。
Public Sub test()
Dim wbk As Workbook
Dim Conswbk As Workbook
Dim ConsWS as Worksheet
Dim Temppath As String
Dim PayTemp As String
Dim Path As String
Dim lstactrow As String
Path = "C:\Users\mathew.m.1\Desktop\New folder\"
'Application.DisplayAlerts = False
Set Conswbk = ThisWorkbook
Set ConsWS = Conswbk.Worksheets("Consolidate Payments")
ConsWS.UsedRange.Cells.ClearContents
ConsWS.UsedRange.Cells.ClearFormats
PayTemp = Dir(Path & ".")
'-------------------------------------------- 'OPEN EXCEL FILES
Do While PayTemp > "" 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & PayTemp)
wbk.Range("A12:M1000").copy
'Range("A12:M1000").Select
'Selection.Copy
'Conswbk.Worksheets("Consolidate Payments").Activate
lstactrow = ConsWS.Cells(Rows.Count, "C").End(xlUp).Row
Consws.cells(2,lstactrow+1).paste 'note, may have row/col switched, can never remember
'Range("B" & lstactrow).Select
'ActiveCell.Offset(1, 0).Select
'ActiveCell.PasteSpecial (xlPasteAll)
consWB.cells(1,lstactrow+1) = PayTemp
'Conswbk.Worksheets("Consolidate Payments").Range("A" & lstactrow).Select
'Selection.Offset(1, 0).Select
'ActiveCell.Value = PayTemp
wbk.Close True
Set wbk = Nothing
PayTemp = Dir
Loop
MsgBox ("Done!!!")
set consws = nothing
set conswbk = nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.