0

我有一个范围,我想在每次迭代时在列之间交替写入文件。我会有 A1 > B1 > A2 > B2 等,举个例子:

      A   |   B
1   Hello | World
2   Whats | Up

现在我将它放在一个文本文件中:

Hello
World
Whats
Up

我有以下代码将从我的第一列中获取信息,但我坚持在每次迭代时添加第二列:

Sub mac()
Dim fso As New FileSystemObject
Dim stream As TextStream
Set stream = fso.CreateTextFile("F:\Hmmmmm.txt", True)

  Range("G2").Select

  Do Until IsEmpty(ActiveCell)
     stream.WriteLine ActiveCell
     ' Here I would affectively want stream.WriteLine ActiveCell + 1 Column
     ActiveCell.Offset(1, 0).Select
  Loop

End Sub
4

1 回答 1

1

首先,如果您还没有这样做,请确保您选择了 VBA 编辑器中工具下的“Microsoft 文件脚本”参考(有关更多帮助,请阅读如何在 VBA 中使用 FileSystemObject?)。

以下应该工作。请注意阅读我的评论 - 您可以更改部分代码以适合您的电子表格/需求

Sub mac()
    Dim ws As Worksheet
    Dim fso As New FileSystemObject
    Dim stream As TextStream
    Dim DataTable As Range
    Dim StartCell As Range
    Dim c As Range

    'Edit this line to save the text file to drive\path\filename of your choice
    Const TextFileName As String = "F:\Hmmmmm.txt"       

    Set ws = ActiveSheet
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set stream = fso.CreateTextFile(FileName:=TextFileName, Overwrite:=True)

    'Edit this line to adjust to your spreadsheet
    'I assume your data starts in Cell A1
    Set StartCell = ws.Range("A1")

    Set DataTable = StartCell.CurrentRegion

    For Each c In DataTable.Cells
            stream.WriteLine c.Value
    Next c

    Set c = Nothing
    Set StartCell = Nothing
    Set DataTable = Nothing
    Set ws = Nothing
    Set stream = Nothing
    Set fso = Nothing
End Sub
于 2013-03-17T08:25:15.213 回答