Automate Text Import in Excel 2007

后端 未结 3 1492
鱼传尺愫
鱼传尺愫 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:40

    I ended up making some tweaks to the function before putting it into use.

    Public Sub OpenCsv()
        ' I don't expect any more columns than 256 in my environment, so I can 
        ' just fill this array and call it done.
        Dim columnFormats(0 To 255) As Integer
        For i = 0 To 255
            columnFormats(i) = xlTextFormat
        Next i
    
        Dim filename As Variant
        filename = Application.GetOpenFilename("All Files (*.*),*.*", 1, "Open", "", False)
        ' If user clicks Cancel, stop.
        If (filename = False) Then
            Exit Sub
        End If
    
        Dim ws As Excel.Worksheet
        Application.Workbooks.Add
        Set ws = Excel.ActiveSheet
        Application.DisplayAlerts = False
        Sheets("Sheet2").Delete
        Sheets("Sheet3").Delete
        Application.DisplayAlerts = True
    
    
        With ws.QueryTables.Add("TEXT;" & filename, ws.Cells(1, 1))
            .FieldNames = True
            .AdjustColumnWidth = True
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileCommaDelimiter = True
            ''// This array will need as many entries as there will be columns:
            .TextFileColumnDataTypes = columnFormats
            .Refresh
        End With
    End Sub
    

    Thanks to the above guys for getting me going.

提交回复
热议问题