Export sheet as UTF-8 CSV file (using Excel-VBA)

后端 未结 3 1243
小鲜肉
小鲜肉 2020-12-16 07:17

I would like to export a file I have created in UTF-8 CSV using VBA. From searching message boards, I have found the following code that converts a file to UTF-8 (from this

3条回答
  •  太阳男子
    2020-12-16 07:37

    Update of this code. I used this one to change all .csv files in a specified folder (labeled "Bron") and save them as csv utf-8 in another folder (labeled "doel")

    Sub SaveAsUTF8()
    
    Dim fsT As Variant, tFileToOpen As String, tFileToSave As String
    Dim Message As String
    Dim wb As Workbook
    Dim fileName As String
    
    Set wb = ActiveWorkbook
    
    With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
    End With
    
    Message = "Source folder incorrect"
    SourceFolder = wb.Worksheets("Menu").Range("Bron") & "\"
    If Dir(SourceFolder, vbDirectory) = "" Or IsEmpty(SourceFolder) Then GoTo errorhandler
    
    Message = "Target folder incorrect"
    TargetFolder = wb.Worksheets("Menu").Range("Doel") & "\"
    If Dir(TargetFolder, vbDirectory) = "" Or IsEmpty(TargetFolder) Then GoTo errorhandler
    
    fileName = Dir(SourceFolder & "\*.csv", vbNormal)
    
    Message = "No files available."
    If Len(fileName) = 0 Then GoTo errorhandler
    
    Do Until fileName = ""
    
        tFileToOpen = SourceFolder & fileName
        tFileToSave = TargetFolder & fileName
    
        tFileToOpenPath = tFileToOpen
        tFileToSavePath = tFileToSave
    
    Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object
    fsT.Type = 2: 'Specify stream type – we want To save text/string data.
    fsT.Charset = "utf-8": 'Specify charset For the source text data.
    
    fsT.Open: 'Open the stream
    fsT.LoadFromFile tFileToOpenPath: 'And write the file to the object stream
    
    fsT.SaveToFile tFileToSavePath, 2: 'Save the data to the named path
    
    fileName = Dir()
    
    Loop
    
    Message = "Okay to remove all old files?"
    If QuestionMessage(Message) = False Then
        GoTo the_end
    Else
        On Error Resume Next
        Kill SourceFolder & "*.csv"
        On Error GoTo errorhandler
    End If
    
    the_end:
    With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
    End With
    Exit Sub
    
    errorhandler:
    With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
    End With
    CriticalMessage (Message)
    Exit Sub
    
    End Sub
    
    '----------
    
    Function CriticalMessage(Message As String)
    
    MsgBox Message
    
    End Function
    
    '----------
    
    Function QuestionMessage(Message As String)
    
    If MsgBox(Message, vbQuestion + vbYesNo) = vbNo Then
    QuestionMessage = False
    Else
    QuestionMessage = True
    End If
    
    End Function
    

提交回复
热议问题