這裏有2種方式,以節省列到文本文件:
Option Explicit
Private fso As Variant
Sub saveColsToText()
Const START_COL As Long = 2
Const START_ROW As Long = 2
Const FNAME_ROW As Long = 2
Const F_PATH As String = "C:\Temp\"
Dim ws1 As Worksheet, ws2 As Worksheet, thisCol As Range
Dim lr As Long, lc As Long, i As Long, colStr As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
With ws1
lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
lr = .Cells(.Rows.Count, 1).End(xlUp).Row
For i = START_COL To lc
Set thisCol = .Range(.Cells(1, i), .Cells(lr, i))
colStr = Join(Application.Transpose(thisCol.Value2), vbCrLf)
saveColToFile1 F_PATH, ws2.Cells(FNAME_ROW, i).Value2 & ".txt", colStr
Next
End With
End Sub
Sub saveColToFile1(ByVal fPath As String, ByVal fName As String, ByVal colText As String)
Dim fileID As Variant
If Len(Dir(fPath)) = 0 Then MkDir fPath
Set fileID = fso.CreateTextFile(fPath & fName, True)
fileID.Write colText
fileID.Close
Set fileID = Nothing
End Sub
Sub saveColToFile2(ByVal fPath As String, ByVal fName As String, ByVal colText As String)
Open fPath & fName For Output As #1
Write #1, colText
Close #1
End Sub
'------------------------------------------------------------------------------------------
嘿@CDH,歡迎SO!你更具體地經歷了什麼錯誤?什麼是'catch'? – Klaster
不清楚?像這樣說... 1.你需要什麼...... 2.你的代碼是什麼...... 3.代碼的問題是什麼......!這樣發佈。 –
嗨@Klaster,我有一張c.400列的表格,我想將每列保存爲一個.txt文件。問題在於我需要使用另一個工作表上指定的名稱來保存文件(全部按照列的順序)。它需要兩個循環 - 一個保存列和一個尋找名稱。我認爲。道歉,我對VBA很陌生。 – CDH