如何在VBA中从2个未连接的范围写入文本文件

我正在尝试使用VBA代码将电子表格中的一系列数据写入一个txt文件,我将其导入到一个统计程序(如STATA)中。

我想写的范围的第一列是,例如,“A1:A25”。 第二列是用户select的范围,例如“C1:C25”

到目前为止,我所尝试的代码只有在两列彼此相邻时(列A和列B)才有效。 如果它们没有连接(列A和C),那么文件将列A和列C写入一个长列数据到txt文件而不是两列。

这是我到目前为止所尝试的代码。 提前致谢。

Sub testwrite() Dim rng1 As Range Dim rng2 As Range Dim newRng As Range path = ActiveWorkbook.path Set rng1 = ActiveSheet.Range("A1:A25") Set rng2 = Application.InputBox("Select a column of data", "Obtain Range Object", Type:=8) Set rng = Union(rng1, rng2) Dim check As String Dim c As Range, r As Range Dim output As String For Each r In rng.Rows For Each c In r.Cells output = output & "," & c.Value Next c output = output & vbNewLine Next r Open path & "\text_data3.txt" For Output As #1 Print #1, output Close End Sub 

如果这是列A和C

 A | C ======= 1 A 2 B 3 C 

和你正在寻找的输出是

 1,A 2,B 3,C 

你不想使用联合,你会循环一个范围,然后另一个。 你可以循环遍历你想要的输出的范围。

 Sub testwrite() Dim rng1 As Range Dim rng2 As Range Dim newRng As Range Dim Path As String Dim r As Variant Dim i As Integer Dim rows As Integer Path = ActiveWorkbook.Path Set rng1 = ActiveSheet.Range("A2:A25") Set rng2 = Application.InputBox("Select a column of data", "Obtain Range Object", Type:=8) rows = rng1.Count Dim output As String For i = 1 To rows Step 1 output = output & rng1.rows(i).Value & "," & rng2.rows(i).Value & vbCrLf Next i Open Path & "\text_data3.txt" For Output As #1 Print #1, output Close End Sub 

我已更正您的代码。 一切都是相似的,但你select的范围转换为数组。

 Sub testwrite() Dim ar1 As Variant Dim ar2 As Variant Dim Path As String Dim i As Long 'counter Dim output As String Path = ActiveWorkbook.Path ar1 = ActiveSheet.Range("A1:A25").Value ar2 = Application.InputBox("Select a column of data", _ "Obtain Array Data", Type:=64) For i = 1 To UBound(ar1, 1) output = output & "," & ar1(i, 1) & "," & ar2(i, 1) & vbNewLine Next Open Path & "\text_data3.txt" For Output As #1 Print #1, output Close End Sub