在VB中覆盖文件的内容

时间:2014-11-24 14:25:13

标签: vba vbscript

我正在阅读文件列表,并且沿途都会有更新版本。在我的循环中,我正在检查文件是否已经存在并尝试将其删除,以便我可以再次创建更新的版本:

objFs = CreateObject("Scripting.FileSystemObject")

If (objFs.FileExists(location & "\" & fileName & ".xml")) Then
    System.IO.File.Delete(location & "\" & fileName & ".xml")
End If

objTextStream = objFs.CreateTextFile(location & "\" & fileName & ".xml", True)
objTextStream.Write(System.Text.Encoding.UTF8.GetString(recordXml))

理想情况下,如果文件已经存在并且覆盖了内容,我宁愿打开文件,但到目前为止,我的尝试仍然存在。

location是用户定义的路径,例如C://

recordXML是从数据库中检索到的值

我一直遇到的主要错误是

Additional information: Argument 'Prompt' cannot be converted to type 'String'.

这似乎意味着该文件要么不在那里删除,要么在我尝试创建它时它已经存在。删除可能无法正常工作,可能是文件未及时删除以重新创建它?...

无论如何,这是我的想法。

3 个答案:

答案 0 :(得分:0)

http://www.mrexcel.com/forum/excel-questions/325574-visual-basic-applications-check-if-folder-file-exists-create-them-if-not.html找到此代码,用于创建新文件(除非已经存在),然后打开它(现有的或新的)。打开后,您只需执行Sheets( NAMEOFSHEET").Cells.Clear清除单元格,然后粘贴数据。

Sub btncontinue_Click()
Dim myFile As String, myFolder As String
myFolder = "C:\TimeCards"
myFile = myFolder & "\timecards.xls"
If Not IsFolderExixts(myFolder) Then
    CreateObject("Scripting.FileSystemObject").CreateFolder myFolder
End If
If Not IsFileExists(myFile) Then
    MsgBox "No such file in the folder"
    Exit Sub
End If
Set wb = Workbooks.Open(myFile)
' Your code here
End Sub

Function IsFolderExists(txt As String) As Boolean
    IsFolderExists = _
        Createobject("Scripting.FileSystemObject").FolderExists(txt)
End Function

Function IsFileExists(txt As String) As Boolean
    IsFileExists = _
        CreateObject("Scripting.FilesystemObject").FileExists(txt)
End Function

答案 1 :(得分:0)

你可以尝试这个,它应该在VB,VBA和VBScript中工作。

objFs = CreateObject("Scripting.FileSystemObject")

If objFs.FileExists(location & "\" & fileName & ".xml") Then Kill(location & "\" & fileName & ".xml")

Open location & "\" & fileName & ".xml" For Output As #1
Print #1, recordXml
Close #1

答案 2 :(得分:0)

尝试使用FSO删除文件。 objTextStream也需要 set ,因为它是对象。

Sub AnySub()
Dim objFs As FileSystemObject
Set objFs = CreateObject("Scripting.FileSystemObject")

If (objFs.FileExists(Location & "\" & Filename & ".xml")) Then
    objFs.DeleteFile Location & "\" & Filename & ".xml"
End If
Set objTextStream = objFs.CreateTextFile(Location & "\" & Filename & ".xml", True)

objTextStream.Write recordXml

End Sub

我不确定.write方法是否适用于UTF8。 我正在使用这个功能:

Sub File_WriteToUTF8(File_Path As String, s_Content As String)
On Error GoTo ende

Dim LineStream As Object
Set LineStream = CreateObject("ADODB.Stream")
With LineStream
    .Type = 2
    .Mode = 3
    .Charset = "utf-8"
    .Open
    .WriteTEXT s_Content
    .SaveToFile File_Path, 2
ende:
    .Close
End With
End Sub

所以而不是

objTextStream.Write recordXml

它将是

File_WriteToUTF8 Location & "\" & Filename & ".xml", recordXml