如下所示的EXCEL表格中,怎么將從第2行開始的每行資訊以A列單元格為檔案名另存為TXT檔案。
例如,將第2行另存為以“111”為檔案名的TXT,TXT打開后顯示為:111 d ddd
代碼 特性1 特性2
111 d dd
222 e ee
333 f ff
444 g gg
555 h hh
666 i ii
uj5u.com熱心網友回復:
寫段簡單的 Excel VBA 代碼,供參考。打開Excel(打開檔案)、再打開VBE,插入一個“標準模塊”,添加如下代碼:
Option Explicit
Public Sub Main()
Dim strPath As String
Dim strTemp As String
Dim i As Long
strTemp = InputBox("請輸入保存txt檔案的路徑:", "檔案路徑")
If ("" = strTemp) Then
Call MsgBox("沒有指定輸出路徑,終止操作。", 64&, "提示資訊")
Exit Sub
End If
strPath = strTemp & "\"
i = 2& ' 資料從第2行開始
Do
' 假設資料在當前作業簿的 Sheet1 中
strTemp = Trim$(Sheet1.Cells(i, 1).Value)
If ("" = strTemp) Then Exit Do ' 空單元格結束
Open strPath & strTemp & ".txt" For Output As #1
Print #1, strTemp; vbTab;
Print #1, Sheet1.Cells(i, 2).Value; vbTab;
Print #1, Sheet1.Cells(i, 3)
Close #1
i = 1& + i
Loop
If (2& = i) Then
Call MsgBox("沒有資料輸出。", 64&, "提示資訊")
Else
Call MsgBox("輸出操作完成。", 64&, "提示資訊")
End If
End Sub
uj5u.com熱心網友回復:
上面第22行代碼,不小心少輸入了 .Value ,應為:Print #1, Sheet1.Cells(i, 3).Value
不過,也可以省略.Value ,試了一下,默認屬性應該是跟 .Value 屬性值相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/48513.html
標籤:VBA
