我找到了替换文件名中的invalids字符的函数。我想将它用于一个文件夹中的所有文件。
Function strLegalFileName(strFileNameIn As String) As String
Dim i As Integer
Const strIllegals = "\/|?*<>"":"
strLegalFileName = strFileNameIn
For i = 1 To Len(strIllegals)
strLegalFileName = Replace(strLegalFileName, Mid$(strIllegals, i, 1), "_")
Next i
End Function
我不知道如何在包含invalids时遍历所有文件并替换字符。
呼叫功能是否正常?通过Debug.print命令 循环遍历所有文件,但我不确定如何构建它:
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, FileName As Variant
FileName = Dir("C:\Users\Anna\Desktop\testNazwa\")
While (file <> "")
Debug.Print strLegalFileName(strFileNameIn)
file = Dir
Wend
End Sub
答案 0 :(得分:2)
你有一些问题
Dir
循环以下代码执行此操作。请更改StrDir
以适合
但是我注意到,因为这些charcaters是非法的,所以文件名开头应该是无效的(因此我的测试会查看不同的字符)
循环并重命名代码
Sub LoopThroughFiles()
Dim FName As Variant
Dim strNew As String
Dim strDir As String
strDir = "C:\temp\"
FName = Dir(strDir & "*.*")
Do While Len(FName) > 0
strNew = strLegalFileName(FName)
If StrComp(strNew, FName) <> 0 Then Name (strDir & FName) As (strDir & strNew)
FName = Dir
Loop
End Sub
字符串替换功能
Function strLegalFileName(ByVal FName) As String
Dim i As Integer
Const strIllegals = "P:"
strLegalFileName = FName
For i = 1 To Len(strIllegals)
strLegalFileName = Replace(strLegalFileName, Mid$(strIllegals, i, 1), "_")
Next i
End Function
Regexp功能替代
Function strLegalFileName(ByVal FName) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "[\/\\\?\*\]\[\|:]"""
.Global = True
strLegalFileName = .Replace(FName, vbNullString)
End With
End Function