我正在嘗試將我的作業簿匯出到文本檔案,但如果單元格中有逗號,我的代碼會在匯出的檔案中添加引號。
下面是我的代碼。任何幫助表示贊賞。
Sub ExportFile()
Dim wb As Workbook
Dim saveFile As String
Dim WorkRng As Range
Dim r As Long
On Error Resume Next
r = Worksheets("sheet1").Cells(Rows.Count, "A").End(xlUp).Row
Set WorkRng = Range(Cells(2, 1), Cells(r, 99))
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).Paste
saveFile = Application.GetSaveAsFilename(InitialFileName:="output", fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
電流輸出: 電流輸出
期望的輸出: 期望的輸出
uj5u.com熱心網友回復:
上面評論中發布的鏈接中的任何答案都將提供一個很好的解決方案。就我個人而言,我通常希望對輸出進行更多控制,并且通常撰寫自己的解決方案。您選擇自己的道路.... :)
編輯:添加代碼以洗掉每行末尾的“掛起”分隔符,以及整個緩沖區末尾的“掛起”vbNewLine。
Option Explicit
Sub ExportThisSheet()
Dim thisWS As Worksheet
Set thisWS = Sheet1
Dim lastRow As Long
Dim workArea As Range
With thisWS
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set workArea = .Range(.Cells(2, 1), .Cells(lastRow, 99))
End With
Const DELIMITER As String = vbTab 'change to " " ?
Dim workRow As Variant
Dim textLine As String
Dim textResult As String
For Each workRow In workArea.Rows
textLine = vbNullString
Dim i As Long
For i = 1 To workArea.Columns.Count
'--- optionally check if the Value is empty and skip if you want
textLine = textLine & workRow.Cells(1, i).Value & DELIMITER
Next i
'--- delete the extra DELIMITER
textLine = Left$(textLine, Len(textLine) - 1)
textResult = textResult & textLine & vbNewLine
Next workRow
'--- delete the last newline
textResult = Left$(textResult, Len(textResult) - 1)
Dim saveFilename As String
saveFilename = Application.GetSaveAsFilename(InitialFileName:="output", _
FileFilter:="Text Files (*.txt), *.txt")
Open saveFilename For Output As #1
Print #1, textResult
Close #1
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452100.html
