我正在尝试读取一个充满 XML 文件的文件夹并将参考编号更改为特定格式,即今天的日期(yymmdd),首字母缩写,从 00000001 开始的 8 位参考
例如 120815AB00000001 然后 120815AB00000002 等等。每个文件都有一个参考号。它包含在 <CPAReferenceNumber> 标记中。
我正在使用 Excel 和 VBA 来读取文件并更改相关字段。引用设置为默认值(在下面的代码中,它现在将“This”更改为“That”)
此代码适用于一个单独的文件并进行正确的更改。这些文件具有随机名称,并且没有适当的命名约定。我无法将其扩展到文件夹中的所有 XML 文件。任何帮助将不胜感激。
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
sFileName = "c:\Search and Replace Files\blah.XML"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
帮助后,我将其修改为以下代码,但这会导致错误: sFileName is out of context。文本更改不适用于 xml 文件。
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
Const sSearchString As String = "c:\blah\*.xml"
Const directoryString As String = "c:\blah\"
iFileNum = FreeFile
sFileName = Dir(sSearchString)
Do While sFileName <> ""
Open directoryString & sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "IDNUMBER", "******SUCCESS!!!!!!******")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
Debug.Print "Do something with file named " & sFileName
sFileName = Dir()
Loop
End Sub