生成Excel文件到.txt文件并做一些循环
我想生成.txt文件的Excel文件,并做一些循环。 比如像这样:
在Excel中:
A | B | C | D --+---+---+--- 1 | 5 | 9 | 1 A | H | U | I
将这样生成为.txt文件:
"A", "1" "B", "5" "C", "9" "D", "1" "A", "A" "B", "H" "C", "U" "D", "I"
编辑:这是我的编码
Private Sub CommandButton1_Click() Dim sFirst As String Dim sSecond As String Dim sThird As String Dim sFourth As String Dim sFName As String Dim intFNumber As Integer Dim lHeader As Long Dim lLastRow As Long Sheet1.Activate Range("A1").Select With Sheet1 lLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With sFName = ThisWorkbook.Path & "\Date" & Format(Now(), "yyyymmddhhmmss") & ".xls" 'Get an unused file number intFNumber = FreeFile 'Create a new file (or overwrite an existing one) Open sFName For Output As #intFNumber For lHeader = 1 To lLastRow With Sheet1 'For header sFirst = .Cells(lHeader, 1) sSecond = .Cells(lHeader, 2) sThird = .Cells(lHeader, 3) sFourth = .Cells(lHeader, 4) End With 'Write selected data to text file Write #intFNumber, sFirst, sSecond , sThird, sFourth Next lHeader Close #intFNumber MsgBox "Values from sheet '" & Sheet1.Name & "' were written to '" & sFName & "' file!", vbInformation End Sub
但它只是这样产生的:
"A", "1" "B", "5" "C", "9" "D", "1"
尝试这个:
'Write selected data to text file Write #intFNumber, "A", sFirst Write #intFNumber, "B", sSecond Write #intFNumber, "C", sThird Write #intFNumber, "D", sFourth
而不是这个:
Write #intFNumber, sFirst, sSecond , sThird, sFourth
更换
Write #intFNumber, sFirst, sSecond , sThird, sFourth
同
Print #intFNumber, sFirst , sSecond , sThird, sFourth & Chr(10)
要添加新行,请添加& Chr(10)
或& vbNewLine