【发布时间】:2017-08-21 19:04:26
【问题描述】:
我正在循环以复制文件夹中所有文件的所有标题。当我尝试关闭文件时出现错误。这发生在 with 语句中。基本上我从我的桌面打开文件,复制标题,我无法关闭文件,因为我收到了错误 Object Required
如果您需要更多详细信息,请告诉我。提前谢谢!
Sub LoopAllExcelFilesInFolder()
Dim wb, y, export As Workbook
Dim myPath, CopyPath, CopyFile As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim LR As Long
Dim rgCut As Excel.Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
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
Set rgCut = wb.Worksheets(1).Range("A1").EntireRow
Set y = Workbooks.Open("C:\Users\icohen\Desktop\exceltest.xlsx")
Workbooks.Open("C:\Users\icohen\Desktop\exceltest.xlsx").Activate
LR = Cells(Rows.Count, 1).End(xlUp).Row
With y
Sheets(1).Cells.Select
If LR = 0 Then
rgCut.Copy Destination:=Selection.Range("A1")
Else
rgCut.Copy Destination:=Selection.Range("A" & LR)
.Save ' Here i receive the error
.Close ' Here i receive the error
End If
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
【问题讨论】:
-
您是否尝试过指定 y.save 和 y.close?由于前面的语句在选择中执行命名范围剪切和粘贴,尽管有 With 语句,它可能会混淆系统。
-
你打开同一个工作簿两次:你只需要
y.Activate。 -
谢谢西里尔!我之所以喜欢这个只是因为我有其他错误:(我发现复制的方式适合这样。
-
摆脱
Sheets(1).Cells.Select...使用rgCut.Copy Destination:=Sheets(1).Range("A1") -
@Mat'sMug,你是绝对正确的。但是如果有人重命名工作表,那么代码将失败,而不是践踏所有工作表(1)