Esc
user@example.com
View Profile
intermediate copy-paste macros

VBA Macro: Import & Clean a Solver CSV

Open a solver-output CSV (e.g. from PowerFactory or a Python script), parse it into a sheet, drop blank/duplicate rows, coerce numeric columns, and apply the standard table format.

Run via Alt+F8 → ImportSolverCSV. Asks for the CSV path with the file picker, then writes the cleaned table to a new worksheet.

ImportSolverCSV.bas
Option Explicit

Sub ImportSolverCSV()
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Select solver CSV"
    fd.Filters.Clear
    fd.Filters.Add "CSV files", "*.csv"
    If Not fd.Show Then Exit Sub

    Dim path As String
    path = fd.SelectedItems(1)

    Dim wsNew As Worksheet
    Set wsNew = ThisWorkbook.Sheets.Add(After:=Sheets(Sheets.Count))
    wsNew.Name = "Imported " & Format(Now, "hh-mm-ss")

    Dim fh As Integer
    fh = FreeFile
    Open path For Input As #fh

    Dim row As Long: row = 1
    Dim line As String, parts() As String, i As Long
    Do While Not EOF(fh)
        Line Input #fh, line
        If Trim(line) = "" Then GoTo NextLine
        parts = Split(line, ",")
        For i = 0 To UBound(parts)
            Dim v As String
            v = Trim(parts(i))
            If IsNumeric(v) Then
                wsNew.Cells(row, i + 1).Value = CDbl(v)
            Else
                wsNew.Cells(row, i + 1).Value = v
            End If
        Next i
        row = row + 1
NextLine:
    Loop
    Close #fh

    If row <= 1 Then
        MsgBox "No data rows found in " & path, vbExclamation
        Exit Sub
    End If

    Dim used As Range
    Set used = wsNew.UsedRange
    used.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes

    used.Select
    Call FormatResultsTable

    MsgBox "Imported " & (used.Rows.Count - 1) & " rows from " & path, vbInformation
End Sub