【问题标题】:VBA Excel Export Rows to Columns in .txtVBA Excel 将行导出到 .txt 中的列
【发布时间】:2017-11-09 16:24:33
【问题描述】:

有谁知道如何在 Excel 中编写 VBA 以将多行导出到一列。此外,我想在每个“行”的末尾添加“输入”。理想情况下,这将以 .txt 格式导出,但即使在同一个文档中进行转换,它也已经很棒了。

谢谢!

编辑:例如:我的行包含一些文本/值 A1:A5、B1:B5、...例如,我需要所有这些行在单个列 D 中“移动”。所以,A1 会去 D1,A2-D2,A3-D3 ... B1 到 D7 等等。在每一端(A5、B5、C5、...)之后,我需要一个空单元格(当我将其转换为 .txt 时,它意味着输入)。我希望现在清楚一点。

【问题讨论】:

标签: excel vba


【解决方案1】:

您需要添加参考 Microsoft ActiveX Data Objects 2.8 Library

Set ff = CreateObject("ADODB.Stream")
ff.Type = 2
ff.Charset = "utf-8"
ff.Open

For Each Cell In Range("A1:D5").Cells
ff.WriteText Cell.Value & vbNewLine
Next

path_to_save = ActiveWorkbook.Path

ff.SaveToFile path_to_save & "\test.txt", 2

【讨论】:

    【解决方案2】:

    下面的代码将按照您的描述进行。使用开头的常量设置应移动到一列的列数和行数,由 TargetColNo 指定。每扫描一列后都会添加一个空单元格。

    如果您希望将其保存到文本文件,您可以使用此代码并添加一个文本文件来添加结果而不是列。

    Sub Rows2OneColumn()
        Const StartColumnNo = 1 ' Start at column A
        Const EndColNo = 3      ' End at column C
        Const StartRowNo = 1    ' Start at row 1
        Const EndRowNo = 5      ' End at row 5
    
        Const TargetColNo = 5   ' Put result in column E
    
        Dim source_row As Integer
        Dim source_col As Integer
        Dim target_row As Integer
    
        target_row = 1
    
        For source_col = StartColumnNo To EndColNo
            For source_row = StartRowNo To EndRowNo
                Cells(target_row, TargetColNo).Value = Cells(source_row, source_col).Value
                target_row = target_row + 1
            Next
            target_row = target_row + 1 ' leave one cell empty
        Next
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      相关资源
      最近更新 更多