把Excel匯入TXT檔案
阿新 • • 發佈:2021-11-17
一,Open語句方式,程式碼如下:
Sub Excel資料存入txt檔案() Dim arr, brr Dim str As String, ptr As String Dim row As Integer, num As Integer arr = Range("A1").CurrentRegion ptr = ThisWorkbook.Path & "\database\工作表資料.txt" num = FreeFile Open ptr For Output As #num For row = 1 To UBound(arr) brr = WorksheetFunction.Index(arr, row, 0) str = Join(brr, ",") Print #num, str Next row Close #num End Sub
二,ADO的Stream物件連線方式,程式碼如下:
Sub Excel寫入txt檔案() Dim stm As New ADODB.Stream Dim ptr As String Dim str As String Dim arr, brr, i As Integer arr = Range("A1").CurrentRegion ptr = ThisWorkbook.Path & "\database\資料.txt" With stm .Charset = "utf-8" '檔案編碼格式,可以GB2312,Unicode .Open For i = 1 To UBound(arr) brr = WorksheetFunction.Index(arr, i, 0) str = Join(brr, ",") .WriteText str, adWriteLine Next i .SaveToFile ptr, adSaveCreateOverWrite .Close End With Set stm = Nothing End Sub