在VBA中一次选择一个或多个文件

时间:2014-07-14 21:27:06

标签: excel-vba vba excel

我一直致力于让宏一次选择一个文件或同时选择两个文件。如果用户首先选择一个文件,则选择的第二个文件(在不同目录中找到)将其放在第一个文件名下面,但不要替换第一个文件名。如果用户选择两个文件,则将它们放在另一个文件之后。这是我到目前为止所做的,当用户只选择一个文件时它不起作用,因为它没有在相应的单元格中显示文件的名称。它在我选择两个文件时有效但在我只选择一个文件时它不起作用。任何帮助表示赞赏。

strInitialDirectory = CurDir
Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd
    .Title = "Choose File"
    .InitialFileName = CurDir & "\"
    .AllowMultiSelect = True
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xls;*.xlsx;*.xlsm"

    If .Show = False Then
        ChDir (strInitialDirectory)
        Exit Sub
    End If
        If fd.SelectedItems.Count > 1 Then
            strPathAndOne = .SelectedItems(1)
            strPathAndTwo = .SelectedItems(2)
        Else
                strPathAndOne = .SelectedItems(1)
                mvUp = True
        End If
 End With

 strFileOne = Right(strPathAndOne, Len(strPathAndOne) - InStrRev(strPathAndOne, "\"))
 strFileTwo = Right(strPathAndTwo, Len(strPathAndTwo) - InStrRev(strPathAndTwo, "\"))

    If mvUp = True Then
        ThisWorkbook.Sheets("Sheet1").Range("E4") = strFileTwo
    Else
        ThisWorkbook.Sheets("Sheet1").Range("E3") = strFileOne
        ThisWorkbook.Sheets("Sheet1").Range("E4") = strFileTwo
    End If


 End Sub

2 个答案:

答案 0 :(得分:1)

使用F8进行单循环以查看正在进行的操作。或者做debug.print' s。如果mvUp为True,那么我认为你想要strFileOne而不是strFileTwo。

答案 1 :(得分:0)

以下列方式更改IsEmpty(" E3")IsEmpty(范围(" E3"))。

 If fd.SelectedItems.Count = 2 Then
            strPathAndOne = .SelectedItems(1)
            strPathAndTwo = .SelectedItems(2)

    ElseIf fd.SelectedItems.Count = 1 Then
            If IsEmpty(Range("E3")) = True Then
                strPathAndOne = .SelectedItems(1)
            ElseIf IsEmpty(Range("E4")) = True Then
                strPathAndTwo = .SelectedItems(1)
            End If
    End If
End With

 strFileOne = Right(strPathAndOne, Len(strPathAndOne) - InStrRev(strPathAndOne, "\"))
 strFileTwo = Right(strPathAndTwo, Len(strPathAndTwo) - InStrRev(strPathAndTwo, "\"))

    If IsEmpty(Range("E3")) = True And IsEmpty(Range("E4")) = True Then
        ThisWorkbook.Sheets("Sheet1").Range("E3") = strFileOne
        ThisWorkbook.Sheets("Sheet1").Range("E4") = strFileTwo
    ElseIf IsEmpty(Range("E3")) = True Then
        ThisWorkbook.Sheets("Sheet1").Range("E3") = strFileOne
    ElseIf IsEmpty(Range("E4")) = True Then
        ThisWorkbook.Sheets("Sheet1").Range("E4") = strFileTwo
    End If
相关问题