循环浏览文件只会打开第一个文件

时间:2018-12-07 10:25:58

标签: excel vba

我已经阅读了有关Stack Overflow的所有答案,但无法解决此问题。 我正在尝试打开文件夹中的每个文件,但是“ Do While”循环操作可以正确打开第一个文件,执行任务,保存文件,然后再次打开第一个文件。如何获取下一个文件?

Sub loopmacro()
    Dim psheet As Worksheet
    Dim imppath As String
    Dim impfile As String
    Dim exppath As String
    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Dim thiswb As Workbook
    Dim opsheet As Worksheet

    Set thiswb = ThisWorkbook
    impfile = Sheets("LOOKUPS").Range("C13")
    imppath = Dir(impfile)
    Application.ScreenUpdating = False
    If Dir(impfile) = "" Then
        MsgBox "There are no files in the PASTE CSV FOLDER"
    Else
        Do While imppath <> ""
            Set wb1 = Workbooks.Open(impfile)
            wb1.Activate
            thiswb.Activate
            Call clear_paste_csv_data_sheet
            wb1.Activate
            Range("A1:F1000").Copy
            thiswb.Activate
            Sheets("Paste CSV here").Select
            Range("A1").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            Application.CutCopyMode = False
            wb1.Close
            thiswb.Activate
            Call calc_data_lines
            exppath = thiswb.Sheets("LOOKUPS").Range("C17")
            Set wb2 = Workbooks.Add
            thiswb.Activate
            Sheets("CNV OUTPUT").Range("A1:A1000").Copy
            wb2.Activate
            Sheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues
            Application.CutCopyMode = False
            wb2.SaveAs Filename:=exppath
            wb2.Close
            imppath = Dir
        Loop
    End If
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

此行仅引用文件夹,而不引用文件夹中的文件:

Set wb1 = Workbooks.Open(impfile)  

应为:

Set wb1 = Workbooks.Open(impfile & imppath)  

这表明您可能错误地使用了变量名。
看来您应该具备:

impPath = Sheets("LOOKUPS").Range("C13")  

impfile = Dir(imppath)  

然后这将按逻辑读取:

Set wb1 = Workbooks.Open(imppath & impfile)