我的excel表中有一個自定義按鈕,當用戶單擊它時,代碼使用戶能夠上傳檔案,然后代碼修改上傳的檔案,并將修改后的內容存盤在一個字串變數中s。——
Option Explicit
Sub Button1_Click()
Dim fso As Object, ts As Object, doc As Object
Dim data As Object, filename As String
Dim ws As Worksheet
Set ws = ActiveSheet
' select file
With Application.FileDialog(msoFileDialogFilePicker)
If .Show <> -1 Then Exit Sub
filename = .SelectedItems(1)
End With
' read file and add top level
Set doc = CreateObject("MSXML2.DOMDocument.6.0")
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpentextFile(filename)
doc.LoadXML Replace(ts.readall, "<metadata>", "<root><metadata>", 1, 1) & "</root>"
ts.Close
' import data tag only
Dim s As String
Set data = doc.getElementsByTagName("data")(0)
s = data.XML
' MsgBox s
' replace the original XML file with contents of variable s here
If MsgBox(s & vbCrLf, vbYesNo) = vbYes Then
Application.SendKeys ("%lt")
Else
MsgBox "Ok"
End If
End Sub
假設我單擊了按鈕并上傳了一個 XML 檔案C:/My Folder/sample.xml。現在代碼修改它,并更新檔案(使用存盤在變數中的新內容s)。下面是一張代表圖——(修改的內容是s變數的直接值)

我如何實作上述目標?請指導...謝謝!
uj5u.com熱心網友回復:
請參閱TextStream 物件的CreateTextFile 方法
Set ts = fso.CreateTextFile(filename, True)
ts.Write s
ts.Close
uj5u.com熱心網友回復:
為什么不通過再次加載所需的字串(在 之后Set data = doc.getElementsByTagName("data")(0))繼續使用 XML 方法:
doc.LoadXML data.XML
doc.Save filename
已發布代碼的旁注
值得一提的是,開始<root> 和結束</root>標記以某種方式奇怪地插入到加載的 xml 字串中
doc.LoadXML Replace(ts.readall, "<metadata>", "<root><metadata>", 1, 1) & "</root>"
是重建格式良好的 xml 輸入的唯一解決方法,從而避免
Error `-1072896683 XML document must have a top level element.`
因此,imo您可能會考慮更改模式檔案以包含不在頂層的元資料,而是包含在設計中的后續層次結構級別,以提供可加載的、格式良好的 xml 標記。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363070.html
