我有一个4列的。csv文件。我想把我的excel数据到一个txt文件,但是,我想有不同的列之间的间距选项,他们是在txt文件。
示例-如果行1有四列是[列a = 2列b = 3,列c = 4,列d = 5],文本文件中的输出将是:
2 3 4 5
2和3之间有一个制表符,3和4之间有四个空格,4和5之间有14个空格。这是相当随机的,但格式化是由于以前创建的文件。
我在每个教程中编写了以下代码,但我不确定如何操作它以获得每行不同的间距。
Sub excelToTxt()
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
CellData = vbTab
FilePath = Application.DefaultFilePath & "test.txt"
Open FilePath For Output As #2
For i = 1 To LastRow
For j = 1 To LastCol
If j = LastCol Then
CellData = CellData + Trim(ActiveCell(i, j).Value)
Else
CellData = Trim(ActiveCell(i, j).Value) + CellData
End If
Next j
Write #2, CellData
CellData = vbTab
Next i
Close #2
End
有人能帮助解决这个问题吗? 你可以这样写:
Dim spacing As Variant
Select Case Cells(i, j).Column
Case 1: spacing = vbTab
Case 2: spacing = Space(4) - Len(Cells(i, j).Value)
Case 3: spacing = Space(14) - Len(Cells(i, j).Value)
End Select
Write #2, Cells(i, j).Value & spacing
您必须修改写入值的部分。检查你要写的是哪一列,并在两列之间添加你需要的值。
就像这样。
For j = 1 To LastCol
If j = LastCol Then
CellData = CellData + Trim(ActiveCell(i, j).Value)
Elseif j = 1 Then
CellData = Trim(ActiveCell(i, j).Value) + CellData
Elseif j = 2 Then
CellData = Trim(ActiveCell(i, j).Value) + vbTab
Elseif j = 3 Then
CellData = Trim(ActiveCell(i, j).Value) + " "
Elseif j = 4 Then
CellData = Trim(ActiveCell(i, j).Value) + " "
Elseif j = 5 Then
CellData = Trim(ActiveCell(i, j).Value) + " "
End If
Next j
Write #2, CellData
CellData = vbTab