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

时间:2015-07-03 08:32:25

标签: excel excel-vba vba

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

一个例子是:

spreadsheet data:

column1 column2 column3 column4

 id     title    body   personid

txt file : (should be)

id,title,body,personid
每行

1 个答案:

答案 0 :(得分: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