Excel 在Vba中打开文本文件,获取错误1004
我有一个系统生成的文件,扩展名为00010002,以此类推。这些文件在记事本中可以作为文本文件进行编辑。下面的VBA代码正在工作,但突然出现了问题 “错误1004-无法获取的替换属性。” 工作表函数类” 我编写了下面的代码来读取文件,查找并删除WHT,并在找到WHT的特定位置添加空格。代码运行正常,但出现此错误Excel 在Vba中打开文本文件,获取错误1004,excel,vba,string,replace,Excel,Vba,String,Replace,我有一个系统生成的文件,扩展名为00010002,以此类推。这些文件在记事本中可以作为文本文件进行编辑。下面的VBA代码正在工作,但突然出现了问题 “错误1004-无法获取的替换属性。” 工作表函数类” 我编写了下面的代码来读取文件,查找并删除WHT,并在找到WHT的特定位置添加空格。代码运行正常,但出现此错误 Sub RemoveWHTaddspaces() Dim Textfile as integer Dim Filepath as String Dim FileContent as S
Sub RemoveWHTaddspaces()
Dim Textfile as integer
Dim Filepath as String
Dim FileContent as String
Dim Check1 as integer
Dim Check2 as Integer
Filepath = Application.Getopenfilename()
Textfile=Freefile
Open FilePath For Input as Textfile
Filecontent = Input(LOF(Textfile), Textfile)
Close Textfile
Do
Check1=Instr(Filecontent, "WHT ")
Filecontent=Application.worksheetfunction.Replace(Filecontent,Check1,4,"")
Filecontent=Application.worksheetfunction.Replace(Filecontent,Check1+38,25,"
")
Check1=Instr(Filecontent, "WHT ")
Loop while Check1>0
Textfile = Freefile
Open Filepath For Output as Textfile
Print #Textfile, Filecontent
Close Textfile
Msgbox ("Done")
Reset
End Sub
您需要检查是否找到匹配项 试试这个
Check1 = InStr(FileContent, "WHT ")
If Check1 > 0 Then '<~~~~~
FileContent = Application.WorksheetFunction.Replace(FileContent, Check1, 4, "")
FileContent = Application.WorksheetFunction.Replace(FileContent, Check1 + 38, 25, " ")
Check1 = InStr(FileContent, "WHT ")
End if
Check1=InStr(文件内容,“WHT”)
如果选中1>0,则“是”匹配存在。我已经更正了子名称中的键入错误(&in)。如果没有匹配项,您将得到错误。我知道你在找“WHT”后面的空格。您确定文本文件中是空格而不是其他不可打印的字符吗?您可能希望手动删除文本文件中的空格,然后使用空格键再次插入?是的,我必须删除带有空格的文本。有许多相同的实例,因此我无法删除空间并再次添加。请尝试使用其中一个,然后查看。