【问题标题】:VBA FilesystemObjectVBA 文件系统对象
【发布时间】:2014-07-24 05:35:09
【问题描述】:

我在使用 VBA 中将某些列保存到文本文件的函数时遇到问题。 它只保存 B 列的值,并忽略另一个 for 循环,其中我在 C 列的值中循环。我尝试添加直接写入文件 - > objTextStream.writeline ("COPY THIS STRING") 只是为了查看问题出在哪里,但仍然 COPY THIS 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

【问题讨论】:

  • 首先我认为你应该写objTextStream.writeline "COPY THIS STRING" 不带()

标签: vba excel


【解决方案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

【讨论】:

  • 谢谢。当我刚开始使用 VBA 时,我可以对此进行后续调查吗?我可以选择将其保存为 .SQL 格式而不是文本文件吗?我当前使用的函数是 CreateTextFile()
  • 当然,澄清一下就好了。
  • 我可以选择将其保存为 .SQL 格式而不是文本文件吗?我当前使用的函数是 CreateTextFile()
  • 如果“SQL 格式”是指插入数据库,请使用不同的对象(例如 ado)。如果您的意思是将 SQL 命令文件创建为文本,fso 很好,只需在创建文件时指定不同的文件扩展名。
  • 哦,明白了。我正在指定 SQL 的不同文件扩展名,但它不起作用但我发现路径中缺少“\”。感谢顺便说一句的帮助。非常感谢。
猜你喜欢
  • 2012-04-09
  • 2013-08-25
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多