vba txt讀寫的幾種方式


四種方式寫txt

1、這種寫出來的是ANSI格式的txt

   Dim TextExportFile As String
    
    TextExportFile = ThisWorkbook.Path & "\lcx.txt"
    
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.CreateTextFile(TextExportFile, True)

    f.WriteLine "羅彩霞:lcx"
    f.Close

2、這種是Unicode格式

    Dim TextExportFile As String
    
    TextExportFile = ThisWorkbook.Path & "\lcx.txt"
    
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.CreateTextFile(TextExportFile, True, True)

    f.WriteLine "羅彩霞:lcx"
    f.Close

3、這種是UTF-8格式的

Sub WriteTxt(path_, Filename, k)

    Dim tss As String
     
    'Filename = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
    
    Open path_ & "\" & Filename For Output As #1
     
    For i = 1 To k
        If Cells(i, 4).Value <> "" Then
            tss = Cells(i, 4) & vbTab & Cells(i, 5) & vbTab & Cells(i, 6) & vbTab & Cells(i, 7) & vbTab & Cells(i, 8) & vbTab & Cells(i, 9)
            Print #1, tss
        End If
    Next
     
    Close #1
    
End Sub

4、這種方式可以設置字符格式

Sub WriteUTF8()
    Dim WriteStream As Object
    Set WriteStream = CreateObject("ADODB.Stream")
    With WriteStream
        .Type = 2               'adTypeText
        .Charset = "UTF-8"
        .Open
        .WriteText "你好utf-8"
        .SaveToFile ThisWorkbook.path & "\1.txt", 2  'adSaveCreateOverWrite
        .Flush
        .Close
    End With
    Set WriteStream = Nothing
End Sub

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM