vba 文本在应该附加时被覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11126551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:21:16  来源:igfitidea点击:

Text is being over written when it's supposed to be appended

vbafile-iofilesystemobject

提问by Tim

This seems really easy (I've done it a million times and never had a problem), but it's killing me.

这看起来真的很容易(我已经做了一百万次并且从来没有出现过问题),但它让我很伤心。

I want to create some SQL scripts based on content in an Excel spreadsheet. To do this I've created a macro that reads a text file using the code below

我想根据 Excel 电子表格中的内容创建一些 SQL 脚本。为此,我创建了一个使用以下代码读取文本文件的宏

Dim fso As FileSystemObject
Set fso = New FileSystemObject

Dim stream As TextStream
Set stream = fso.OpenTextFile(filepath, 8, False)

This is supposedto open the text file for appending and plug in my new values.

应该打开文本文件以追加并插入我的新值。

Unfortunately, it's always overwritinginstead of appending, and it's driving me nuts.

不幸的是,它总是覆盖而不是附加,这让我发疯。

Any ideas?

有任何想法吗?

回答by Scott Holtzman

I just recently built a function to Append Strings to a File. I came across this issue just a few weeks / months ago and found that if used the actual word ForAppending, just as it shows up in Intellisense, insted of the number 8it worked for me.

我最近刚刚构建了一个将字符串附加到文件的函数。几周/几个月前,我遇到了这个问题,发现如果使用实际的ForAppending一词,就像它在 Intellisense 中显示的那样,插入对我有用的数字8

Const ForAppending = 8

Sub AppendStringToFile(ByVal strFile As String, ByVal strNewText As String, Optional intBlankLine As Integer = 1)

Dim fso as FileSystemObject, ts as TextStream

Set fso = New FileSystemObject
Set ts = fso.OpenTextFile(strFile, ForAppending, True)

With ts
    .WriteBlankLines intBlankLine
    .WriteLine (strNewText)
    .Close
End With

Set ts = Nothing
Set fso = Nothing

End Sub

回答by SeanC

Drop back to basics....
Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

回到基础......
Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

used for your requirements:

用于您的要求:

Dim FNum As Integer

FNum = FreeFile()
Open strFile For Append As FNum

'do your stuff here
Write #FNum, MyData

Close FNum

回答by vergenzt

It's very odd, in this documentation, it mentions that the constant corresponding to ForAppendingis 8, but it uses 3in the example at the bottom.

很奇怪,在这个文档中,它提到了对应于ForAppendingis的常量8,但它3在底部的示例中使用。

Try:

尝试:

Dim fso As FileSystemObject
Set fso = New FileSystemObject

Dim stream As TextStream
Set stream = fso.OpenTextFile(filepath, 3, False)