如何在 Excel 中將每一行匯出或儲存為文字檔案


Excel 是微軟開發的一款強大的電子表格程式。它廣泛用於各個行業和職業中組織、分析和處理資料。要將 Excel 中的多個列匯出到各個文字檔案中,可以使用 VBA(Visual Basic for Applications)宏。

在 Excel 中將每一行匯出或儲存為文字檔案的步驟

以下是如何操作的示例

步驟 1:開啟您想要將行匯出為文字檔案的 Excel 檔案。按 Alt + F11 在 Excel 中開啟 Visual Basic 編輯器。

透過點選“插入”並選擇“模組”插入一個新的模組。在模組視窗中,貼上以下程式碼

示例

Sub ExportRowsAsTextFiles()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim rowNum As Long
    Dim rowRange As Range
    Dim cellValue As String
    Dim filePath As String
    Dim cell As Range
    
    Set ws = ThisWorkbook.ActiveSheet ' Change to the appropriate sheet if needed
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' Assumes data starts in column A
    
    ' Loop through each row
    For rowNum = 1 To lastRow
        ' Set the range for the current row
        Set rowRange = ws.Range("A" & rowNum & ":" & ws.Cells(rowNum, ws.Columns.Count).End(xlToLeft).Address)
        
        ' Initialize cellValue as an empty string
        cellValue = ""
        
        ' Loop through each cell in the row
        For Each cell In rowRange
            ' Check the data type of the cell value
            Select Case True
                Case IsNumeric(cell.Value) ' Numeric value
                    cellValue = cellValue & CStr(cell.Value) & ","
                Case IsDate(cell.Value) ' Date value
                    cellValue = cellValue & Format(cell.Value, "dd-mm-yyyy") & ","
                Case Else ' Text value or other types
                    cellValue = cellValue & CStr(cell.Value) & ","
            End Select
        Next cell
        
        ' Remove the trailing comma
        cellValue = Left(cellValue, Len(cellValue) - 1)
        
        ' Define the file path for the text file (change as needed)
        filePath = "E:\Assignments\3rd Assignments\How to export or save each row as text file in Excel\Output\file_" & rowNum & ".txt"
        
        ' Export the row as a text file
        Open filePath For Output As #1
        Print #1, cellValue
        Close #1
    Next rowNum
    MsgBox "Rows exported to individual text files."
End Sub

步驟 2:根據需要修改程式碼:

  • 將“ws”變數設定為要從中匯出行的工作表。預設情況下,它從活動工作表匯出。

  • 調整 ws.Range("A" & rowNum & ":" & ws.Cells(rowNum, ws.Columns.Count).End(xlToLeft).Address) 中的列引用以匹配您想要匯出的列範圍。

  • 將 filePath 變數更新到您想要儲存文字檔案的目標路徑。示例程式碼將它們儲存為 file_1.txt、file_2.txt 等檔名,在我的資料夾中。確保將路徑更改為有效的目錄。

步驟 3:按 Alt + F8 執行宏,選擇“ExportRowsAsTextFiles”,然後點選“執行”。

程式碼將遍歷指定工作表中的每一行,將該行中的值連線成一個逗號分隔的字串,並將其儲存為具有指定檔案路徑的文字檔案。每一行都將擁有自己的文字檔案。

結論

要將 Excel 檔案中的每一行匯出為單獨的文字檔案,您可以使用 VBA(Visual Basic for Applications)程式碼。程式碼遍歷指定工作表的每一行,將該行中的值連線成一個逗號分隔的字串。然後,該字串將儲存為具有唯一檔案路徑的文字檔案,每個檔案對應一行。

程式碼包括錯誤處理,以處理行中的不同資料型別。它檢查一個值是否為數字、日期或屬於“其他”類別,後者涵蓋文字和其他型別。應用適當的轉換,並將值追加到 cellValue 變數。生成的字串使用指定的檔案路徑儲存為文字檔案。此過程確保 Excel 檔案中的每一行都匯出為單獨的文字檔案,以便在 Excel 之外進行進一步分析或處理。

更新於: 2023年7月20日

4K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告