我正在循环输入文件并使用readline命令读取每一行,检查它是否有各种标准,然后我想根据结果进行更改。这是我正在尝试做的一个非常简单的版本:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileLoc, 1)
Do While Not objFile.AtEndOfStream
strLineRead = objFile.readline
if strLineRead Like "*text to change*" Then
'Some code to change the line
end if
Loop
我一直在做的是将整个文件保存到名为strFileText的字符串中,然后使用Replace函数将该字符串中的strLineRead替换为更改后的版本。像这样:
strFileText = Replace(strFileText, strLineRead, strNewLine)
然后将整个字符串写入新的文本文件。
问题是,有时我可能会有一行,其中整个文本是“NC”,然后对整个文件进行“NC”的查找/替换不仅仅更改一行。
在FileSystemObject中是否有一个命令,在某一行上,能够直接修改文件?我在想类似“写作线”的命令。
答案 0 :(得分:1)
在您的文件和事件中的某个地方拥有这些私人潜艇,请打电话给他们。首先调用replace_text并填写要求。请参阅我的示例代码。
Private Sub Command3_Click()
Dim sFileName As String
Dim fileSys As Variant
' Edit as needed
sFileName = Me.FileList.Value
Set fileSys = CreateObject("Scripting.FileSystemObject")
Replace_Text sFileName, "bad text", "good text", fileSys
End Sub
Private Sub Replace_Text(targetFile As String, targetText As String, replaceText As String, fileSys As Variant)
If Right(targetFile, 3) = "filepath extension you want (example: xml or doc etc.)" Then
Update_File targetFile, targetText, replaceText, fileSys
Else
MsgBox "You did not select the right file. Please try again."
End If
End Sub
Private Sub Update_File(fileToUpdate As String, targetText As String, replaceText As String, fileSys As Variant)
Dim tempName As String
Dim tempFile As Variant
Dim file As Variant
Dim currentLine As String
Dim newLine As String
'creates a temp file and outputs the original files contents but with the replacements
tempName = fileToUpdate & ".tmp"
Set tempFile = fileSys.CreateTextFile(tempName, True)
'open the original file and for each line replace any matching text
Set file = fileSys.OpenTextFile(fileToUpdate)
Do Until file.AtEndOfStream
currentLine = file.ReadLine
newLine = Replace(currentLine, targetText, replaceText)
'write to the new line containing replacements to the temp file
tempFile.WriteLine newLine
Loop
file.Close
tempFile.Close
'delete the original file and replace with the temporary file
fileSys.DeleteFile fileToUpdate, True
fileSys.MoveFile tempName, fileToUpdate
End Sub