Skip to content

Instantly share code, notes, and snippets.

@iso2022jp
Created November 12, 2012 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iso2022jp/4057845 to your computer and use it in GitHub Desktop.
Save iso2022jp/4057845 to your computer and use it in GitHub Desktop.
VBA: Convert character encoding
Option Explicit
Public Sub ConvertEncoding(ByRef SourcePath As String, ByRef DestinationPath As String, ByRef SourceEncoding As String, ByRef DestinationEncoding As String)
Dim oWork As Object
With CreateObject("ADODB.Stream")
' load source
.Type = 2 ' adTypeText
.Charset = SourceEncoding
Call .Open
Call .LoadFromFile(SourcePath) '
Set oWork = CreateObject("ADODB.Stream")
With oWork
.Type = 2 ' adTypeText
.Charset = DestinationEncoding
Call .Open
End With
' Convert
Call oWork.WriteText(.ReadText(-1)) ' adReadAll
Call .Close
End With
If LCase$(DestinationEncoding) <> "utf-8" Then
' OK, write
Call oWork.SaveToFile(DestinationPath, 2) ' adSaveCreateOverWrite
Call oWork.Close
Else
' strip BOM
With oWork
.Position = 0
.Type = 1 ' adTypeBinary
.Position = 3 ' BOM
End With
With CreateObject("ADODB.Stream")
.Type = 1 ' adTypeBinary
Call .Open
' Convert UTF-8 with BOM to UTF-8
Call .Write(oWork.Read(-1)) ' adReadAll
Call oWork.Close
Call .SaveToFile(DestinationPath, 2) ' adSaveCreateOverWrite
Call .Close
End With
End If
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment