将多个.CSV导入到启用宏的工作表

时间:2014-07-09 12:33:34

标签: excel excel-vba csv vba

我在一个文件夹中有多个(确切地说是5个).csv,并且我想制作一个宏,让我选择文件夹中的csv文件并将它们导入到启用宏的空白文件中。以下是我想要做的一步一步:

  1. 打开main.xlsm
  2. 按工具栏中的宏按钮,显示"导入CSV"
  3. 这将自动打开浏览器窗口,让您在某处找到CSV
  4. 按Ok和BOOM!就像所有你的csv被导出为xlsm并且是当前空白表中的单独表格一样
  5. 我尝试了许多不同的方法,但我不认为我走的是正确的道路。这是一个:

    Sub convert_to_macro()
    
        'This first line is crap though. It only lets you export it to a certain place
    
        ChDir "C:\Users\pal\Documents\CMSe\Lucys Computer"
    
        With Application.FileDialog(msoFileDialogFilePicker)
          .Show
            If .SelectedItems.Count = 0 Then
                MsgBox "Cancel Selected"
                Exit Sub        
            End If
    
            something = .SelectedItems(1)
        End With
    
        ActiveWorkbook.SaveAs Filename:= _
        "something.xltm", _
        FileFormat:=xlOpenXMLTemplateMacroEnabled, Password:="", WriteResPassword _
        :="", ReadOnlyRecommended:=False, CreateBackup:=False
    
    End Sub
    

    感谢您给予的任何帮助

1 个答案:

答案 0 :(得分:0)

像这样将所有csv添加到单个文件中。

Sub convert_to_macro()
Dim Wb As Workbook
Dim Wb1 As Workbook
Dim fd As FileDialog
Dim strWB

Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
    'set initial directory to search
    .InitialFileName = "c:\temp"
    .Filters.Clear
    .Filters.Add "csv files", "*.csv"
    .Show
    If .SelectedItems.Count = 0 Then
           MsgBox "No selection, exiting"
            Exit Sub
    End If
End With

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
End With

Set Wb = Workbooks.Add(1)

For Each strWB In fd.SelectedItems
Set Wb1 = Workbooks.Open(strWB)
Wb1.Sheets(1).Copy after:=Wb.Sheets(Wb.Sheets.Count)
Wb1.Close False
Next

Wb.Sheets(1).Delete

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .DisplayAlerts = True
End With

End Sub