【问题标题】:Writing from .csv to txt file but with differing space patterns between the columns从 .csv 写入 txt 文件,但列之间的空间模式不同
【发布时间】:2015-10-16 14:13:45
【问题描述】:

我有一个包含 4 列的 .csv 文件。我想将我的 excel 数据放入一个 txt 文件中,但是,我希望它们在 txt 文件中的列之间有不同的间距选项。

示例 - 如果第 1 行有四列是 [column a = 2 column b = 3, column c = 4, and column d = 5],文本文件中的输出将是:

2       3    4              5

2 和 3 之间有一个制表符,3 和 4 之间有 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 

有人能帮忙解决这个问题吗?

【问题讨论】:

    标签: vba csv export-to-text


    【解决方案1】:

    你可以使用类似的东西:

    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
    

    【讨论】:

      【解决方案2】:

      您必须修改要写出值的部分。检查您正在写出的列,并在列之间添加您需要的值。

      类似的东西。

          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
      

      【讨论】:

      • 如果您认为您发现了重复的问题,请将其标记出来,而不是发布重复的答案。如果不是重复,则根据问题的具体情况调整您的答案,
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多