建一個資料夾,把目標txt檔案和excel檔案放入其中,在excel的宏編輯器中寫入以下程式碼,有些地方可根據你的實際情況做相應改動:
Sub import_from_txt()
Dim file_name As String, my_path As String
Dim lines, cols
Dim i As Integer, j As Integer, k As Integer, q As Integer
Application.ScreenUpdating = False
Worksheets("Sheet1").Range("A1:Z65536").ClearContents
my_path = ThisWorkbook.Path
file_name = "test.txt"
"讀取檔案
Open my_path & "\" & file_name For Input As #1
lines = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)
Close #1
k = UBound(lines) + 1 "檔案的行數
"遍歷每一行
For i = 1 To k
cols = Split(lines(i - 1), ",") "以逗號作為分隔,將每行字元分割,分隔符可根據實際情況自己修改
q = UBound(cols) + 1 "分隔成的列數
For j = 1 To q "遍歷該行的每一列
Worksheets("Sheet1").Cells(i, j) = cols(j - 1) "輸出到表格中
Next
MsgBox ("檔案" & file_name & "讀取完成,共" & k & "行")
Application.ScreenUpdating = True
End Sub
建一個資料夾,把目標txt檔案和excel檔案放入其中,在excel的宏編輯器中寫入以下程式碼,有些地方可根據你的實際情況做相應改動:
Sub import_from_txt()
Dim file_name As String, my_path As String
Dim lines, cols
Dim i As Integer, j As Integer, k As Integer, q As Integer
Application.ScreenUpdating = False
Worksheets("Sheet1").Range("A1:Z65536").ClearContents
my_path = ThisWorkbook.Path
file_name = "test.txt"
"讀取檔案
Open my_path & "\" & file_name For Input As #1
lines = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)
Close #1
k = UBound(lines) + 1 "檔案的行數
"遍歷每一行
For i = 1 To k
cols = Split(lines(i - 1), ",") "以逗號作為分隔,將每行字元分割,分隔符可根據實際情況自己修改
q = UBound(cols) + 1 "分隔成的列數
For j = 1 To q "遍歷該行的每一列
Worksheets("Sheet1").Cells(i, j) = cols(j - 1) "輸出到表格中
Next
Next
MsgBox ("檔案" & file_name & "讀取完成,共" & k & "行")
Application.ScreenUpdating = True
End Sub