【发布时间】:2017-03-02 16:58:05
【问题描述】:
我想遍历一个包含 Excel 文件的文件夹,对于每个文件,遍历每一行(从第 4 行开始),对于每一行,查看“d”列中的值并将该行粘贴到特定的以“d”列中的值命名的 Excel 文件。
如果文件不存在,则需要在粘贴行之前创建它(粘贴时从第 4 行开始)。新创建文件的文件名将是“d”列中的任何值。
如果文件存在,将附加被复制的行(给定行中 d 列的值)。
我的代码不想遍历所有文件。
Sub CopyRowsIntoAppSpreadsheet()
Dim LastRow As Integer, i As Integer, erow As Integer
Dim AppFileName As String
Dim FilePath As String
Dim MyFolder As String
Dim MyFile As String
Dim wbk As Workbook
On Error Resume Next
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> “”
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(FileName:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 4 To LastRow
Range("d" & i).Select
AppFileName = Selection.Value
Rows(i).Select
Selection.Copy
FilePath = "C:\Users\Gary\Desktop\Ex Folder\" & AppFileName & ".xlsx"
If Not Dir(FilePath, vbDirectory) = vbNullString Then
Workbooks.Open FileName:=FilePath
Worksheets("Sheet1").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.CutCopyMode = False
Else
Dim wkb As Workbook
Set wkb = Workbooks.Add
Rows(4).Select
ActiveSheet.Paste
wkb.SaveAs FileName:=FilePath
Cells.Select
Cells.EntireColumn.AutoFit
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.CutCopyMode = False
End If
Next i
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
MsgBox "Macro has completed! Woot! Woot!"
End Sub
【问题讨论】:
-
所以它可以工作,但不会遍历所有文件?我承认,我通常不使用 dir(myfolder) 的东西,但我会测试一下,看看我是否能提供帮助。
-
现在它只循环最后一个文件两次,然后关闭主循环以结束程序。我没有在目标文件夹中创建任何文件(基于 d 列的值)。我只是想要宏来创建它们。
-
我会做出改变的。对此,我真的非常感激!是的,目前最大的问题是它只循环一两个文件,然后就停止了。
-
它将转到我的文件夹列表中的最后一个文件,这就是它在第一个文件之后停止的原因。
-
行循环似乎工作正常。这似乎是文件夹循环的问题。