Skip to content

Instantly share code, notes, and snippets.

@totomz
Created January 20, 2014 16:36
Show Gist options
  • Select an option

  • Save totomz/8523544 to your computer and use it in GitHub Desktop.

Select an option

Save totomz/8523544 to your computer and use it in GitHub Desktop.
Export an Excel to a SQL-like text file
Sub ExportSQL()
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
CellData = ""
FilePath = Application.ActiveWorkbook.Path & "\insert.sql"
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile(FilePath)
Application.DecimalSeparator = "."
Application.ThousandsSeparator = ""
Application.UseSystemSeparators = False
For Row = 1 To LastRow
CellData = "("
For Col = 1 To LastCol
If Not IsEmpty(ActiveCell(Row, Col)) Then
If IsNumeric(ActiveCell(Row, Col)) Then
CellData = CellData & Replace(Trim(ActiveCell(Row, Col).Value), ",", ".")
Else
CellData = CellData & "'" & Replace(Trim(ActiveCell(Row, Col).Value), "'", "\'") & "'"
End If
If Col <> LastCol Then CellData = CellData & ","
End If
Next Col
oFile.WriteLine CellData & "),"
Next Row
oFile.Close
Set fso = Nothing
Set oFile = Nothing
MsgBox ("Fatto!")
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment