Data Processing & Cleanup Intermediate

CSV Import with Data Types

Import CSV files with automatic data type detection and formatting

13 views

Perfect For:

  • Data migration
  • External data import
  • File processing
VBA Code
Sub ImportCSVWithTypes()
    Dim filePath As String
    Dim ws As Worksheet
    Dim qt As QueryTable
    Dim lastRow As Long, lastCol As Long

    ' Get CSV file path
    filePath = Application.GetOpenFilename("CSV Files (*.csv), *.csv")
    If filePath = "False" Then Exit Sub

    ' Create new worksheet for import
    Set ws = Worksheets.Add
    ws.Name = "Imported_" & Format(Now, "mmdd_hhmm")

    ' Import CSV with QueryTable for better control
    Set qt = ws.QueryTables.Add( _
        Connection:="TEXT;" & filePath, _
        Destination:=ws.Range("A1"))

    With qt
        .TextFileParseType = xlDelimited
        .TextFileCommaDelimiter = True
        .TextFileConsecutiveDelimiter = False
        .RefreshStyle = xlInsertDeleteCells
        .Refresh BackgroundQuery:=False
    End With

    ' Auto-detect and apply data types
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    Dim col As Long
    For col = 1 To lastCol
        ' Check if column contains dates
        If IsDate(ws.Cells(2, col).Value) Then
            ws.Columns(col).NumberFormat = "dd/mm/yyyy"
        ' Check if column contains numbers
        ElseIf IsNumeric(ws.Cells(2, col).Value) And ws.Cells(2, col).Value <> "" Then
            ws.Columns(col).NumberFormat = "0.00"
        End If
    Next col

    ' Auto-fit columns
    ws.Columns.AutoFit

    qt.Delete
    MsgBox "CSV imported successfully with " & lastRow & " rows and " & lastCol & " columns!"
End Sub

Related Topics

csv import data types formatting

Need Custom VBA Solutions?

Our AI-powered VBA generator can create custom code tailored to your specific requirements in seconds.

Generate Custom VBA Code

Related Templates

More VBA templates in the same category

Beginner

Data Processing & Cleanup

Remove duplicates, clean data formats, and standardise entries

View Template