-1
我有這兩個潛艇將文本文件導入到Excel工作簿。但是,我擁有的代碼將導入所有選定的文件。如何修改此代碼以限制用戶只選擇50個或更少的文件?此外,程序必須通知用戶導入的最後一個文件的名稱。限制文件導入到50個文件vba
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
非常感謝您的幫助! :) – user3163920
當我們的程序處理大量的文件時,我的程序變得很瘋狂。有沒有辦法修改上面的代碼,只循環前50個文件? – user3163920