Created
November 12, 2012 06:41
-
-
Save iso2022jp/4057845 to your computer and use it in GitHub Desktop.
VBA: Convert character encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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