0

I want to convert Excel file data to Notepad file in UTF-8 Format using Macro and I am using below code. However, if I use

Set ts = FSO.CreateTextFile(textname, overwrite:=True, Unicode:=False)

then some file is created in ANSI Format.

If I use

Set ts = FSO.CreateTextFile(textname, overwrite:=True, Unicode:=False)

then files are created in UTF-16 LE format.

I need the files to be generated in UTF-8 format only.

Sub SplitAndSaveFile1()

    Const batch = 60000
    Const LASTCOL = "AG" ' 33 columns

    Dim wb As Workbook
    Dim startrow As Long, lastrow As Long, endrow As Long
    Dim folder As String, partname As String, textname As String
    Dim text As String, s As String
    
    Dim n As Long, i As Long, j As Long
    Dim t0 As Single: t0 = Timer
    
    Set wb = ThisWorkbook
    folder = wb.Path & "\"
    partname = Replace(wb.Path + "\" + wb.Name, ".xlsm", "") + "_Part"
    
    Dim FSO As Object, ts As Object, ar, fields
    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    n = 0
    With wb.Sheets("Data")
        lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        ar = .Range("A4:" & LASTCOL & lastrow).Value
        
        For startrow = 1 To UBound(ar) Step batch
            n = n + 1
            endrow = startrow + batch - 1
            If endrow > UBound(ar) Then endrow = UBound(ar)
            
            ' create text file
            textname = partname & Format(n, "00") & ".txt"
            Set ts = FSO.CreateTextFile(textname, overwrite:=True, Unicode:=True)
            ' ascii false
            
            ' write data as tab delimited
            For i = startrow To endrow
                ReDim fields(1 To UBound(ar, 2))
                For j = 1 To UBound(fields)
                    fields(j) = ar(i, j)
                Next
                If i = endrow Then
                    ts.write Join(fields, vbTab) ' last line no CRLF
                Else
                    ts.writeline Join(fields, vbTab)
                End If
            Next
            ts.Close
        Next
    End With
    MsgBox n & " File(s) generated.", vbInformation, Format(Timer - t0, "0.0 secs")
    
End Sub
James Z
  • 12,104
  • 10
  • 27
  • 43

0 Answers0