将每行电子表格导出为单独的.text文件

问题描述 投票:0回答:1

我有一个包含500行和4列的电子表格。我想将每一行保存到一个单独的TXT文件中,并用逗号分隔每一行。

一个例子是:

spreadsheet data:

column1 column2 column3 column4

 id     title    body   personid

txt file : (should be)

id,title,body,personid

对于每一行。

excel excel-vba vba
1个回答
3
投票

试试这个。

Sub SaveWorksheet()
Dim MyWorkbook As Workbook
Dim MyDataWorksheet As Worksheet

Set MyWorkbook = Workbooks(ActiveWorkbook.Name)
Set MyDataWorksheet = MyWorkbook.Sheets("Data")

Dim OutputFile As String
Dim CellValue As String
Dim CurrentRow As Long
Dim CurrentCol As Long
Dim CurrentCharacter As Long
Dim LastRow As Long
Dim MyString As String

LastRow = MyDataWorksheet.Cells(Rows.Count, "a").End(xlUp).Row

For CurrentRow = 2 To LastRow
'C:\Users\lengkgan\Desktop\Testing\sample.txt
OutputFile = "C:\Users\lengkgan\Desktop\Testing\sample" & CurrentRow & ".txt"

Open OutputFile For Output As #1

    CellValue = MyDataWorksheet.Cells(CurrentRow, 1).Value & "," & MyDataWorksheet.Cells(CurrentRow, 2).Value & "," & MyDataWorksheet.Cells(CurrentRow, 3).Value & "," & MyDataWorksheet.Cells(CurrentRow, 4).Value
    'Write #1, CellValue
    Print #1, CellValue

Close #1

Next CurrentRow

MsgBox "Done"

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.