仅选择多个csv文件,并使选项卡式xlsx文件获取错误52

时间:2015-08-02 15:12:38

标签: excel-vba filepicker vba excel

我正在尝试导航到功能为GetFilesUserForm的文件夹,然后选择多个csv文件,然后使用子ImportCombineCSVsNavigate制作多标签xlsx文件

我认为函数GetFilesUserForm正在运行,但是ImportCombineCSVsNavigate期待文件夹未选中文件我收到错误52Bad file name or number没有得到如何更改它以使用选定的文件

由于

Option Explicit
Public fPath As String


Sub ImportCombineCSVsNavigate()
'Summary:   Import all CSV files from a folder into separate sheets named    for the CSV filenames
Dim fCSV    As String
Dim wbCSV   As Workbook

'start the CSV file listing
fCSV = Dir(fPath & "*.csv")
Do While Len(fCSV) > 0
    'open a CSV file and move
    Set wbCSV = Workbooks.Open(fPath & fCSV)
    ActiveSheet.Move Before:=ThisWorkbook.Sheets("Helper")
    'ActiveSheet.Move After:=ThisWorkbook.Sheets(Sheets.Count)

    'ready next CSV
    fCSV = Dir
Loop


Set wbCSV = Nothing
End Sub



Function GetFilesUserForm() As String
Dim fd As FileDialog
Dim FileChosen As Integer
Dim filter As String, strPath As String


Set fd = Application.FileDialog(msoFileDialogFilePicker)
strPath = "C:Desktop"
With fd
    .AllowMultiSelect = True
    .Filters.Add "CSV Files", "*.*", 1
    .FilterIndex = 2
    .Title = "Choose CSV File"
    .InitialView = msoFileDialogViewDetails
    '.Show

 FileChosen = fd.Show
   If FileChosen <> -1 Then
      'didn't choose anything (clicked on CANCEL)
       MsgBox "You chose cancel"
       End
   Else

      'display name and path of file chose
        GetFilesUserForm = fd.SelectedItems(1)

   End If
 End With
End Function

1 个答案:

答案 0 :(得分:1)

你如何称呼GetFilesUserForm()子?目前它没有采取任何论据。如果您FileDialogueSelectedItems返回ImportCombineCSVsNavigate(),则可以将其传递到Sub Test() Application.ScreenUpdating = False Call ImportCombineCSVsNavigate(GetFilesUserForm()) Application.ScreenUpdating = True End Sub Sub ImportCombineCSVsNavigate(files As FileDialogSelectedItems) 'Summary: Import all CSV files from a folder into separate sheets named for the CSV filenames Dim wbCSV As Workbook Dim i As Integer For i = 1 To files.Count Set wbCSV = Workbooks.Open(files(i)) ActiveSheet.Move Before:=ThisWorkbook.Sheets("Helper") Next i Set wbCSV = Nothing End Sub Function GetFilesUserForm() As FileDialogSelectedItems Dim fd As FileDialog Dim FileChosen As Integer Dim filter As String, strPath As String Set fd = Application.FileDialog(msoFileDialogFilePicker) strPath = "C:Desktop" With fd .AllowMultiSelect = True .Filters.Add "CSV Files", "*.csv", 1 .FilterIndex = 0 .Title = "Choose CSV File" .InitialView = msoFileDialogViewDetails '.Show End With FileChosen = fd.Show If FileChosen <> -1 Then 'didn't choose anything (clicked on CANCEL) MsgBox "You chose cancel" End End If 'return all the files together as FileDialogSelectedItems Set GetFilesUserForm = fd.SelectedItems End Function 子。

{{1}}