VBA中的文本文件:打开/查找替换/保存/关闭文件

时间:2012-05-03 15:17:08

标签: vba text-files

这是我希望做的伪代码:

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

但是我没有覆盖原始文本文件,而是想“另存为”新文件。

5 个答案:

答案 0 :(得分:9)

为什么要使用记事本?

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

答案 1 :(得分:7)

猜猜我太晚了......

今天遇到了同样的问题;这是我使用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

答案 2 :(得分:6)

只需添加此行

即可
sFileName = "C:\someotherfilelocation"

就在这一行之前

Open sFileName For Output As iFileNum

这个想法是打开并写入不同的文件,而不是你之前读过的文件(C:\filelocation)。

如果您想获得真实感并显示真实的“另存为”对话框,您可以改为:

sFileName = Application.GetSaveAsFilename()

答案 3 :(得分: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文件,

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

答案 4 :(得分:-1)

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

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

do until EOF(1)   

       Input #1, ReadedData
loop**