[英]How can I export from Excel file to a csv file, where the file has leading zeros, in text format?
[英]How can I improve my export from Excel selection to text file?
我正在嘗試將Excel數據導出到單個文本文件。 目前,我下面的代碼將Excel中的選擇內容導出到名為“ AgreementText.txt”的文件中。 我想做兩件事來改善它,但不確定如何:
首先,我要為每個.txt文件加上不同的標題。 文件標題列在每個選擇項左側4個空格的列中。 每次我都可以從該列中獲取標題嗎?
其次,文本當前顯示在文本文件中,並帶有引號。 有什么辦法可以刪除那些?
編輯:第三,我還需要指定默認的其他文件路徑,但是我不確定如何。
提前致謝!
Sub TextFileExport()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
myFile = Application.DefaultFilePath & "\AgreementText.txt"
Set rng = Selection
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End Sub
首先,通過獲取單元格值可以輕松檢索標題。 假設它與所選內容位於同一行,但在右邊四列中,則可以執行以下操作:
myFile = Application.DefaultFilePath & "\" & Selection.Cells(1, Selection.Columns.Count + 4) & ".txt"
Open myFile For Output As #1
其次,您可以使用“ Print
而不是“ Write
來打印不帶引號的內容。 我發現最簡單的方法是只將要編寫的整行構建為一個字符串,然后對每行執行一個Print
命令。
放在一起:
Sub TextFileExport()
Dim myFile As String
Dim rng As Range
Dim line
Dim i As Integer
Dim j As Integer
Set rng = Selection
myFile = Application.DefaultFilePath & "\" & rng.Cells(1, rng.Columns.Count + 4) & ".txt"
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
line = ""
For j = 1 To rng.Columns.Count
line = line & rng.Cells(i, j).Value
If j < rng.Columns.Count Then
line = line & ","
End If
Next
Print #1, line
Next
Close #1
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.