我正在进行循环,以便从文件夹中的所有文件中复制所有标头。当我尝试关闭文件时出现错误。这发生在with语句中。基本上,我从我的桌面打开文件,复制标题,我无法关闭文件,因为我收到了错误需要对象
如果您需要更多详细信息,请与我们联系。提前谢谢!
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
答案 0 :(得分:0)
你需要考虑你的在线多重声明习惯(是吗?),如:
Dim wb, y, export As Workbook
在这个变量列表中,“导出”是一个工作簿,但“wb”和“y”只是变体。如果你想要将它们全部三个声明为工作簿,你需要拼写出来,变量变量;这就是VBA的工作方式:)
Dim wb As Workbook, y As Workbook, export As Workbook
它确实节省了一些在线工作的空间...但我总是在它自己的代码行中做每个声明(Dim ......) - 这是一个选择问题。
除此之外,它不是“Sheets”而是“.Sheets”
With y
.Sheets(1).Cells.Select
虽然你为什么这样做我不知道...... 以下应该做得很好:
y.Sheets(1).Select
Rows("1:1").Copy
y.Sheets(2).Range("A1").Select
ActiveSheet.Paste