我需要帮助PLZ
我有一个excel文件,我想将其中的所有数据导出到文本文件中。
这是源代码:
Sub ExceltoText()
Dim FileName, sLine, Deliminator, x, y, z As String
Dim LastCol, LastRow, FileNumber As Integer
FileName = "C:\Users\Administrateur\Desktop\App vba\ExcToTxt.txt"
Deliminator = "|"
x = "$|0|Les Données de SALARIES"
y = "=|0|Les Données de SALARIES"
z = "=|1|SALARIES|"
LastCol = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
FileNumber = FreeFile
Open FileName For Output As FileNumber
For i = 1 To LastRow
For j = 1 To LastCol
If j = LastCol Then
sLine = z & sLine & Cells(i, j).Value
Else
sLine = sLine & Cells(i, j).Value & Deliminator
End If
Next j
If i = 1 Then i = 2
Print #FileNumber, sLine
sLine = ""
Next i
Close #FileNumber
MsgBox "File generated"
End Sub
在结果中我得到了这种格式的文本文件:
=|1|SALARIES|PSA_etablissement|PSA_SALARIE|
=|1|SALARIES|001|10635|
=|1|SALARIES|001|10637|
但我希望我的文本文件是这样的:
$=|1|SALARIES|PSA_etablissement|PSA_SALARIE|
=|1|SALARIES|001|10635|
=|1|SALARIES|001|10637|
我希望在文本文件的开头添加这些行:
$|0|Les Données de SALARIES
=|0|Les Données de SALARIES
答案 0 :(得分:0)
要在文件开头添加行,就在FOR循环之前添加:
Print #FileNumber, x
Print #FileNumber, y
在迭代更改时将该美元符号放在第一行之前:
If i = 1 Then i = 2
Print #FileNumber, sLine
sLine = ""
要:
If i = 1 Then
i = 2
Print #FileNumber, "$" & sLine
Else
Print #FileNumber, sLine
End If
sLine = ""
答案 1 :(得分:0)
试试这个例程:
在for循环之外添加了两行。
也是'&'并且'='是该行的唯一差异,因此将其作为没有这些符号的变量。
Sub ExceltoText()
Dim FileName As String, sLine As String, Deliminator As String
Dim x As String, y As String, z As String
Dim LastCol As Integer, LastRow As Integer, FileNumber As Integer
FileName = "C:\Users\Administrateur\Desktop\App vba\ExcToTxt.txt"
Deliminator = "|"
x = "$=|1|SALARIES|PSA_etablissement|PSA_SALARIE|"
y = "|0|Les Données de SALARIES"
z = "=|1|SALARIES|"
LastCol = ActiveSheet.Cells.Cells(1, Columns.Count).End(xlToLeft).Column
LastRow = ActiveSheet.Cells.Cells(Rows.Count, 1).End(xlUp).Row
FileNumber = FreeFile
Open FileName For Output As FileNumber
Print #FileNumber, "$" & y
Print #FileNumber, "=" & y
Print #FileNumber, x
For i = 1 To LastRow
For j = 1 To LastCol
If j = LastCol Then
sLine = z & sLine & Cells(i, j).Value
Else
sLine = sLine & Cells(i, j).Value & Deliminator
End If
Next j
Print #FileNumber, sLine
sLine = ""
Next i
Close #FileNumber
MsgBox "File generated"
End Sub