Please, try the next way:
Sub CreateUTFTxtFile() 'it looks to return UTF-16 LE-BOM
Dim rng As Range, LastRow As Long, i As Long
Dim fso As Object, MyFile As Object, boolUnicode As Boolean
Dim myFileName As String
myFileName = "C:\Users\user1\Desktop\temp\output.txt"
LastRow = Range("AU" & rows.count).End(xlUp).row
Set fso = CreateObject("Scripting.FileSystemObject")
boolUnicode = True
Set MyFile = fso.CreateTextFile(myFileName, False, boolUnicode) 'open the file to write Unicode:
For i = 2 To LastRow
MyFile.WriteLine (Range("AU" & i).Value)
Next i
MyFile.Close
End Sub
Edited:
Please, test the next code. It will create a real UTF-8 text file. And the code should be fast:
Private Sub CreateUTFT8tFile() 'UTF-8 BOM for huge files...
Dim rng As Range, LastRow As Long, i As Long
Dim fso As Object, MyFile As Object, boolUnicode As Boolean
Dim myFileName As String, myFileName2 As String, strText As String
myFileName = "C:\Users\user1\Desktop\temp\outputUTF16.txt" 'temporary text container
myFileName2 = "C:\Users\user1\Desktop\temp\output.txt"
LastRow = Range("AU" & rows.count).End(xlUp).row
Set fso = CreateObject("Scripting.FileSystemObject")
boolUnicode = True
If dir(myFileName) <> "" Then Kill myFileName
Set MyFile = fso.CreateTextFile(myFileName, False, boolUnicode) 'open the file to write UTF-16:
For i = 2 To LastRow
MyFile.WriteLine (Range("AU" & i).Value)
Next i
MyFile.Close
strText = readTextUTF16$(myFileName) 'read UTF-16 file, used as container for the case of huge text content
With CreateObject("ADODB.Stream")
.Charset = "utf-8": .Open
.WriteText strText
.SaveToFile myFileName2, 2 'convert to UTF-8 BOM
End With
End Sub
Function readTextUTF16$(f)
With CreateObject("ADODB.Stream")
.Charset = "utf-16": .Open
.LoadFromFile f
readTextUTF16$ = .ReadText
End With
End Function
If you do not like UTF-8 BOM, please use the next version:
Sub CreateUTF8TxtFilesNoBOM() 'UTF-8 no BOM
Dim LastRow As Long, oStream As Object
Dim myFileName As String, arrTxt, strTxt As String
myFileName = "C:\Users\user1\Desktop\temp\output.txt"
LastRow = Range("AU" & rows.count).End(xlUp).row
arrTxt = Application.Transpose(Range("AU2:AU" & LastRow).Value)
strTxt = Join(arrTxt, vbCrLf)
WriteUTF8WithoutBOM strTxt, myFileName
End Sub
Function WriteUTF8WithoutBOM(strText As String, fileName As String)
Dim UTFStream As Object, BinaryStream As Object
With CreateObject("adodb.stream")
.Type = 2: .Mode = 3: .Charset = "UTF-8"
.LineSeparator = -1
.Open: .WriteText strText, 1
.Position = 3 'skip BOM' !!!
Set BinaryStream = CreateObject("adodb.stream")
BinaryStream.Type = 1
BinaryStream.Mode = 3
BinaryStream.Open
'Strips BOM (first 3 bytes)
.CopyTo BinaryStream
.Flush
.Close
End With
BinaryStream.SaveToFile fileName, 2
BinaryStream.Flush
BinaryStream.Close
End Function