我正在尝试运行一个代码,该代码将替换文件夹中的所有excel文件。首先,这是代码:
Dim FileSystem As Object
Dim HostFolder As String
Dim StringA As String
Dim StringB As String
Sub Init()
Application.DisplayAlerts = False
HostFolder = "\\Pc-dell\d\Documentos\LSM2\CLIENTES\SRB CDT 2 PROGRESSO2\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
Application.DisplayAlerts = True
End Sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
If Right(File.Name, 4) = ".xls" Or Right(File.Name, 5) = ".xlsx" Then
With Workbooks.Open(File, False)
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
SwapStringsInActiveWorkbook "l1", "l2", ws
SwapStringsInActiveWorkbook "L1", "L2", ws
SwapStringsInActiveWorkbook "l 1", "l 2", ws
SwapStringsInActiveWorkbook "L 1", "L 2", ws
SwapStringsInActiveWorkbook "loja1", "loja2", ws
SwapStringsInActiveWorkbook "LOJA1", "LOJA2", ws
SwapStringsInActiveWorkbook "loja 1", "loja 2", ws
SwapStringsInActiveWorkbook "LOJA 1", "LOJA 2", ws
SwapStringsInActiveWorkbook "Loja1", "Loja2", ws
SwapStringsInActiveWorkbook "Loja 1", "Loja 2", ws
SwapStringsInActiveWorkbook "LOJA1", "LOJA2", ws
SwapStringsInActiveWorkbook "LOJA 1", "LOJA 2", ws
Next ws
End With
ActiveWorkbook.Save
ActiveWorkbook.Close
End If
Continue:
Next
End Sub
Sub SwapStringsInActiveWorkbook(StringA As String, StringB As String, ws As Worksheet)
On Error Resume Next
ws.Cells.SpecialCells(xlCellTypeConstants).Replace What:=StringA, Replacement:="_AUXTEMPREPL_", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
On Error Resume Next
ws.Cells.SpecialCells(xlCellTypeConstants).Replace What:=StringB, Replacement:=StringA, LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
On Error Resume Next
ws.Cells.SpecialCells(xlCellTypeConstants).Replace What:="_AUXTEMPREPL_", Replacement:=StringB, LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
On Error GoTo 0
End Sub
但是在某个时候,经过一些替换,它会给我一个错误,说它无法打开文件:
“Excel无法打开文件'〜$ PLAN COMPARAT de CUSTOS Rancho Bom Loja2-2015.xlsx',因为文件格式或文件扩展名无效。请检查文件是否已损坏且扩展名是否匹配文件格式。“ (这是来自葡萄牙语的错误消息的翻译,抱歉我无法更改语言)
事实是我在这个文件夹上搜索了,没有这样的文件。有一个名为“PLAN COMPARAT de CUSTOS RB-L2-2015.xlsx”的文件,它是一个缩写。也许它试图打开的文件是不存在的旧文件?
我之前有一个脚本可以在word文件中进行替换,并且它还会尝试打开一些不存在的文件,或者它会尝试打开一个名为“〜$”的文件加上文件的名称存在的。这个“〜$”来自哪里?
我需要一些线索。
答案 0 :(得分:1)
我只是在你找到/删除恶意文件之前建议这样做。替换:
If Right(File.Name, 4) = ".xls" Or Right(File.Name, 5) = ".xlsx" Then
使用:
If Left(File.Name, 2) <> "~$" And (Right(File.Name, 4) = ".xls" Or Right(File.Name, 5) = ".xlsx") Then
这应该只是暂时的解决方法。