11

这是我希望做的伪代码:

Open text File

Find "XXXXX" and Replace with "YYYY"

Save text File As

Close text file

这是我到目前为止所拥有的

Private Sub CommandButton1_Click()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\filelocation"

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, "DIM A", "1.75")
sTemp = Replace(sTemp, "DIM B", "2.00")
sTemp = Replace(sTemp, "DIM C", "3.00")
sTemp = Replace(sTemp, "DIM D", "4.00")

'Save txt file as (if possible)

iFileNum = FreeFile
Open sFileName For Output As iFileNum

Print #iFileNum, sTemp

Close iFileNum

'Close Userform
Unload UserForm1

End Sub

但我不想覆盖原始文本文件,而是想“另存为”到一个新文件。

4

5 回答 5

14

估计我来晚了...

今天遇到同样的问题;这是我的解决方案FileSystemObject

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
于 2017-04-22T18:52:22.127 回答
13

为什么涉及记事本?

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\Temp\test.txt"

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
于 2012-05-03T15:50:06.483 回答
8

只需添加这一行

sFileName = "C:\someotherfilelocation"

就在这条线之前

Open sFileName For Output As iFileNum

这个想法是打开并写入与您之前阅读的文件不同的文件(C:\filelocation)。

如果您想花哨并显示一个真正的“另存为”对话框,您可以这样做:

sFileName = Application.GetSaveAsFilename()
于 2012-05-03T17:44:05.550 回答
0

我遇到了同样的问题并遇到了这个网站。

只需在

...输出为... 命令非常简单且有用。

此外(在 Application.GetSaveAsFilename() 对话框之外)

设置一个**新文件名**非常简单,只需使用

替换命令,因此您可以更改文件名/扩展名

例如。(从第一篇文章开始)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

现在只需设置:

newFilename = replace(sFilename, ".txt", ".csv") 更改扩展名

或者

newFilename = replace(sFilename, ".", "_edit.") 用于不同的文件名

然后就像以前一样

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

我浏览了一个多小时来了解如何重命名 txt 文件,

有许多不同的解决方案,但这可能很容易:)

于 2018-01-05T15:05:35.797 回答
-1

此代码将打开并读取完整文本文件的行该变量“ReadedData”将文本行保存在内存中

Open "C:\satheesh\myfile\Hello.txt" For Input As #1

do until EOF(1)   

       Input #1, ReadedData
loop**
于 2012-12-26T15:37:00.527 回答