VBA文件系统对象

我在VBA中的这个函数有问题,将某些列保存到文本文件。 它只保存B列的值,而忽略另一个循环,其中我循环C列的值。我试图添加一个直接写入文件 – > objTextStream.writeline(“COPY THIS STRING”)看看问题在哪里,但仍然复制这个STRING仍然没有保存在文本文件中。

什么似乎是这个问题。 在此先感谢家伙。

Sub SaveToTxt(toRange As Integer) Dim MyRange As Range Dim MyRange2 As Range Dim objFileSyatem As Object, objTextStream As Object Dim cell As Range Set MyRange = ActiveSheet.Range _ ("B1:B" + CStr(toRange) & Cells(Rows.Count, 1).End(xlUp).Row) Set MyRange2 = ActiveSheet.Range _ ("C1:C" + CStr(toRange) & Cells(Rows.Count, 1).End(xlUp).Row) 'create filesystem and textstream objects, the name of the .txt file 'is one of parameters of CreateTextFile method Set objFileSyatem = CreateObject( _ "Scripting.FileSystemObject") Set objTextStream = objFileSyatem.CreateTextFile( _ "C:\Users\wmeniola\work work work\Ranges deletion\test.txt", True) 'loop through all cells in MyRange and save contents as 'separate lines in newly created .txt file For Each cell In MyRange.Cells objTextStream.writeline (cell.Value) Next For Each cell In MyRange2.Cells objTextStream.writeline (cell.Value) Next objTextStream.writeline ("COPY THIS STRING") objTextStream.Close End Sub 

你的问题是在线

 Set MyRange = ActiveSheet.Range _ ("B1:B" + CStr(toRange) & Cells(Rows.Count, 1).End(xlUp).Row) 

它正在创造一个比预期更大的范围。

例如,如果在列A有100行数据,并且您使用toRange = 100调用sub,则将得到MyRange = B1:B100100 。 这将会在您的文本文件中打印大量的空白行!

我想你只是想

 Set MyRange = ActiveSheet.Range("B1:B" & toRange) 

MyRange2类似

或者,不要打扰传递给toRange ,并使用

 With ActiveSheet Set MyRange = .Range("B1:B" & .Cells(.Rows.Count, 1).End(xlUp).Row) End With