限制文件导入到50个文件vba

时间:2014-02-19 04:54:11

标签: excel-vba vba excel

我有这两个子文件将文本文件导入excel工作簿。但是,我的代码将导入所有选定的文件。如何修改此代码以限制用户仅选择50个或更少的文件?此外,程序必须通知用户导入的最后一个文件的名称。

   Sub CopyData()
    Application.ScreenUpdating = False
    Dim fileDia As fileDialog
    Dim I As Integer
    Dim done As Boolean
    Dim strpathfile As String, filename As String

    I = 1
    done = False

    Set fileDia = Application.fileDialog(msoFileDialogFilePicker)
    With fileDia
        .InitialFileName = "C:\Users\5004239346\Desktop\Subhaac\PD_BACKUP"
        .AllowMultiSelect = True
        .Filters.Clear
        .Title = "Navigate to and select required file."
        If .Show = False Then
            MsgBox "File not selected to import. Process Terminated"
            Exit Sub
        End If
            Do While Not done
            On Error Resume Next
            strpathfile = .SelectedItems(I)
            On Error GoTo 0

            If strpathfile = "" Then
                done = True
            Else
                filename = Mid(strpathfile, InStrRev(strpathfile, "\") + 1, Len(strpathfile) - (InStrRev(strpathfile, "\") + 4))
             If Len(filename) > 31 Then filename = Left(filename, 26)
             Transfer strpathfile, filename
               strpathfile = ""
                I = I + 1
            End If

        Loop
    End With

    Set fileDia = Nothing
    Application.ScreenUpdating = True
    WorksheetLoop

    End Sub

    Sub Transfer(mySource As String, wsName As String)


    Dim wbSource As Workbook
    Dim wsDestin As Worksheet
    Dim lrow As Long

    Set wsDestin = ActiveWorkbook.Sheets.Add(, ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)) 'Add the worksheet at the end
    On Error Resume Next
    wsDestin.Name = wsName 'set the name
    On Error GoTo 0

    Application.DisplayAlerts = False
    If InStr(wsDestin.Name, "Sheet") <> 0 Then wsDestin.Delete: Exit Sub

    Workbooks.OpenText filename:=mySource, _
        Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
        Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
        TrailingMinusNumbers:=True

    Set wbSource = ActiveWorkbook

    With wsDestin
        lrow = .Range("A" & Rows.Count).End(xlUp).Row
        wbSource.Sheets(1).UsedRange.Copy .Range("A" & lrow).Offset(1, 0)
        wbSource.Close False
    End With
    Application.DisplayAlerts = True

End Sub

1 个答案:

答案 0 :(得分:1)

AFAIK你不能限制要选择的文件数量,但是你可以检测所选的数字并对其进行操作

If fileDia.SelectedItems.Count > 50 then
    ' User selected more than 50 files

对于第二个问题,最后选择的文件的名称将是

fileDia.SelectedItems(fileDia.SelectedItems.Count)