【发布时间】:2017-12-07 07:32:53
【问题描述】:
我在这段代码中遇到运行时错误 1004。
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")
With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"
' paste
.Range("E" & LastRow + 1) = rng1
End With
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
我正在使用这段代码从文件夹中的所有excel工作簿中提取从B15到E81的数据。
复制后会激活此代码所在的工作簿
从 E 列中选择最后一个条目
偏移 1 行
将选择粘贴到列激活的单元格
感谢我能找到的所有帮助。提前致谢。
【问题讨论】:
标签: excel copy-paste offset vba