2014-07-24 72 views
0

我在VBA中的這個函數有問題,它將某些列保存到文本文件中。 它只保存列B的值,並忽略另一個for循環,其中我循環列C的值。我試圖添加直接寫入文件 - > objTextStream.writeline(「COPY THIS STRING」)只是要查看問題出在哪裏,但仍然複製此STRING仍然沒有保存在文本文件中。VBA文件系統對象

什麼似乎是問題。先謝謝你們。

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 
+0

首先我覺得你應該寫' objTextStream.writeline「COPY THIS STRING」'without() – Noldor130884

回答

1

你的問題是在該行

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

比您預期這是創造一個更大的範圍內。

例如,如果在列A中有100行數據並且您打電話給toRange = 100,那麼您將得到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 
+0

謝謝你。當我剛開始使用VBA時,能否對此進行跟進調查?我可以選擇將其保存爲.SQL格式而不是文本文件嗎?當前函數im使用的函數是CreateTextFile() –

+0

當然,澄清是好的。 –

+0

我可以選擇將其保存爲.SQL格式而不是文本文件嗎?當前函數im使用的函數是CreateTextFile() –