How can I create text files with special characters in their filenames

后端 未结 2 514
一整个雨季
一整个雨季 2020-12-06 15:19

Demonstration of my problem

  • Open a new Excel workbook and save these symbols 設計師協會 to cell [A1]
  • insert the following VBA code somewhere in th
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 15:49

    You are on the right track with the FileSystemObject. As Morbo mentioned you can late bind this so no reference is set. The FSO has a CreateTextFile function which can be set in unicode so the characters will appear as '??????' in VBA but will write correctly to the filename. Note the second parameter of the CreateTextFile function specifies a unicode string for the filename. The following will do the trick for you:

    Sub test()
        Dim strCRLF As String, strSpecialchars As String, strFilename As String
        Dim oFSO As Object, oFile As Object
    
        strCRLF = StrConv(vbCrLf, vbUnicode)
        strSpecialchars = StrConv(Cells(1, 1), vbUnicode)
        strFilename = "C:\" & Cells(1, 1).Value & ".txt"
    
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oFile = oFSO.CreateTextFile(strFilename, , True)
    
        oFile.Write strSpecialchars & strCRLF
    
        oFile.Close
    
        Set oFile = Nothing
        Set oFSO = Nothing
    End Sub
    

提交回复
热议问题