0

the following code vba does not read Persian letters with a proper encoding ; encoding='UTF-8'

Dim strFile As String
Dim intFile As Integer
Dim strBody As String
strFile = "C:\Plus.csv"
intFile = FreeFile
Open strFile For Input As intFile
strBody = Input(LOF(intFile), intFile)
Close intFile

1 Answers1

0

You can use the Stream object from the Microsoft ActiveX Data Objects library the read the contents of a UTF-8 encoded file.

Early Binding

For early binding, you'll first need to set a reference (Visual Basic >> Tools >> References) to the following library...

Microsoft ActiveX Data Objects x.x Library

Then you can use the keyword New to create an instance of the Stream object, and read the contents of the file...

Dim theStream As ADODB.Stream
Dim theContents As String

Set theStream = New ADODB.Stream

With theStream
    .Charset = "UTF-8"
    .Mode = adModeReadWrite
    .Type = adTypeText
    .Open
    .LoadFromFile "c:\users\domta\desktop\sample.txt"
    theContents = .ReadText
    .Close
End With

Late Binding

For late binding, no reference needs to be set. However you'll need to use the CreateObject method to create an instance of the Stream object, and read the contents of the file.

Dim theStream As Object
Dim theContents As String

Set theStream = CreateObject("ADODB.Stream")

With theStream
    .Charset = "UTF-8"
    .Mode = 3 'adModeReadWrite
    .Type = 2 'adTypeText
    .Open
    .LoadFromFile "c:\users\domta\desktop\sample.txt"
    theContents = .ReadText
    .Close
End With
Domenic
  • 7,844
  • 2
  • 9
  • 17