【发布时间】:2021-06-04 00:10:34
【问题描述】:
我正在寻找一个宏来查找和替换 txt 文件中的值。
txt文件位于路由中
D:\Template\info.txt
这个文件长这样(确实文件有HTML代码,但我这里合成了重要的部分)
The current date and time is: %time%
GPU1 Temperature is: %GPU1T%
GPU1 Fan Speed is: %GPU1F%
GPU1 RPM are: %GPU1R%
GPU2 Temperature is: %GPU2T%
GPU2 Fan Speed is: %GPU2F%
GPU2 RPM are: %GPU2R%
我需要的是一个可以查找和替换以下内容的宏:
Find %time% in the txt file and replace with the value of cell G2
Find %GPU1T% in the txt file and replace with the value of cell A2
Find %GPU1F% in the txt file and replace with the value of cell C2
Find %GPU1R% in the txt file and replace with the value of cell E2
Find %GPU2T% in the txt file and replace with the value of cell B2
Find %GPU2F% in the txt file and replace with the value of cell D2
Find %GPU2R% in the txt file and replace with the value of cell F2
然后,当然保存文件,但在一个新的位置,即
D:\GPUReport
但名称相同info.txt
到目前为止,尝试处理这个宏没有成功
Sub FindAndReplaceText()
Dim FileName As String
Dim FolderPath As String
Dim FSO As Object
Dim I As Integer
Dim SearchForWords As Variant
Dim SubstituteWords As Variant
Dim Text As String
Dim TextFile As Object
SearchForWords = Array("%time%", "%GPU1T%", "%GPU1F%", "%GPU1R%", "%GPU2T%", "%GPU2F%", "%GPU2R% ")
SubstituteWords = Array(Range("G2"), Range("A2"), Range("C2"), Range("E2"), Range("B2"), Range("D2"), Range("F2"))
FolderPath = "D:\Template\info.txt"
Set FSO = CreateObject("Scripting.FileSystemObject")
FolderPath = IIf(Right(FolderPath, 1) <> "\", FolderPath & "\", FolderPath)
FileName = Dir(FolderPath & "\*.txt")
Do While FileName <> ""
Filespec = FolderPath & FileName
Set TextFile = FSO.OpenTextFile(Filespec, 1, False)
Text = TextFile.ReadAll
TextFile.Close
Set TextFile = FSO.OpenTextFile(Filespec, 2, False)
For I = 0 To UBound(SearchForWords)
Replace Text, SearchForWords(I), SubstituteWords(I)
Next I
TextFile.Write Text
TextFile.Close
FileName = Dir()
Loop
End Sub
我希望有人可以帮助我。
非常感谢您!
【问题讨论】:
-
表达式
FileName = Dir(FolderPath & "\*.txt")将搜索带有D:\Template\info.txt\\*.txt掩码的文件。我认为 FileName 总是为空的。也许 FolderPath 必须是“D:\Template”?