从Excel文件VBA循环文件夹名称

时间:2019-04-23 08:40:01

标签: excel vba

我有一个可以复制所需文件的代码 这是代码

Dim saveFolder As String
Dim fname As String

saveFolder = "C:\Copied file"

folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A2")
FileName = Workbooks("Macros.xlsb").Worksheets("path").Range("B4")

Path = FileName & "\" & folder & "\Samples\*.xlsx"
file = Dir(Path)

Workbooks.Open Path

Sheets("Accounts").copy
ActiveWorkbook.SaveAs saveFolder & "\Accounts.xlsx", FileFormat:=51
Workbooks(file).Close

ActiveWorkbook.Close

它运作良好,但是我需要在单元格列中手动输入文件夹名称。但是我只在为1个文件夹完成宏之后单击所有按钮,依此类推。

我只想知道如何循环播放。

这将是我的文件夹名称的工作表(文件夹):

FOLDER
45
118
180
290

我想循环每个单元格的宏。因此,我不需要一一点击/编辑值。因为文件夹名称可以立即更改。

2 个答案:

答案 0 :(得分:0)

在您的问题要求循环之内,您可以尝试...

Dim saveFolder As String
Dim fname As String

Dim lastRow As Long
Dim i As Long

' Set this either statically or dynamically.
lastRow = 100
saveFolder = "C:\Copied file"

' Start from where you want either statically or dynamically.
For i = 4 To lastRow
    folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A2")
    Filename = Workbooks("Macros.xlsb").Worksheets("path").Range("B" & i)

    Path = Filename & "\" & folder & "\Samples\*.xlsx"
    file = Dir(Path)

    Workbooks.Open Path

    Sheets("Accounts").Copy
    ActiveWorkbook.SaveAs saveFolder & "\Accounts.xlsx", FileFormat:=51
    Workbooks(file).Close
Next

ActiveWorkbook.Close

答案 1 :(得分:0)

仅用于将文件从一个位置复制到另一位置,您无需打开并在文件上另存为:)

您可以从上一行到lastRow循环输入文件夹名称,并一一处理文件夹。 查找最后一行 lastRow = wb.sheets("Folder").cells(wb.rows.count, 1).end(xlup).row

现在,通过for循环遍历文件夹名称 for i=2 to lastRow

您可以将文件夹放在循环之内

for i=2 to lastRow
    folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A" & i)
    ...
    copy  operations and filter here
    ...
next i