VBA 中的文本文件:打开/查找替换/另存为/关闭文件 [英] Text file in VBA: Open/Find Replace/SaveAs/Close File

查看:208
本文介绍了VBA 中的文本文件:打开/查找替换/另存为/关闭文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我希望做的伪代码:

Here is pseudocode for what I am hoping to do:

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

但不是覆盖原始文本文件,我想另存为"到一个新文件.

But instead of overwriting the original text file, I want to "save as" to a new file.

推荐答案

只需添加这一行

sFileName = "C:\someotherfilelocation"

就在这条线之前

Open sFileName For Output As iFileNum

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

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

如果你想变得有趣并显示一个真正的另存为"对话框,你可以这样做:

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

这篇关于VBA 中的文本文件:打开/查找替换/另存为/关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆