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

巧了我就是萌 提交于 2020-01-04 09:55:04

问题


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

Dim fso As FileSystemObject
Set fso = New FileSystemObject

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

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

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

Any ideas?


回答1:


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 8 it worked for me.

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



回答2:


Drop back to basics....
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



回答3:


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

Try:

Dim fso As FileSystemObject
Set fso = New FileSystemObject

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


来源:https://stackoverflow.com/questions/11126551/text-is-being-over-written-when-its-supposed-to-be-appended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!