Automate Text Import in Excel 2007

后端 未结 3 1520
鱼传尺愫
鱼传尺愫 2021-01-03 14:39

I\'m trying to write an Excel macro using VBA to automate importing CSV text into a spreadsheet but I\'ve never done it before. I need to make sure that the Text Import Wiz

3条回答
  •  甜味超标
    2021-01-03 15:35

    The code below will allow a user to browse for a csv file.
    It will then :

    • Open the selected file, treating the data as text
    • Resize the columns
    • Move the data into the workbook from which the code is run.

    The .opentext code needs to be updated depending on the number of columns in the source data.

    Sub ImportCSV()
    
    Dim vPath As Variant
    Dim wb As Excel.Workbook
    Dim ws As Excel.Worksheet
    
    Set wb = Excel.ActiveWorkbook
    Set ws = Excel.ActiveSheet
    
    vPath = Application.GetOpenFilename("CSV (Comma Delimited) (*.csv),*.csv" _
    , 1, "Select a file", , False)
    ''//Show the file open dialog to allow user to select a CSV file
    
    If vPath = False Then Exit Sub
    ''//Exit macro if no file selected
    
    Workbooks.OpenText Filename:=vPath, Origin:=xlMSDOS, StartRow:=1 _
        , DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Comma:=True _
        , FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), _
        Array(3, xlTextFormat))
    ''//The fieldinfo array needs to be extended to match your number of columns
    
    Columns.EntireColumn.AutoFit
    ''//Resize the columns
    
    Sheets(1).Move Before:=wb.Sheets(1)
    ''//Move the data into the Workbook
    
    End Sub
    

提交回复
热议问题