我找到了替换文件名中的无效字符的函数。我想将其用于一个文件夹中的所有文件。
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
我不知道如何在所有文件中循环并在包含无效内容时替换字符。
调用功能是否正确?通过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
你有一些问题
Dir
循环下面的代码执行此操作。请更改StrDir
为适合
但我要注意,因为这些字符是ilegal,所以文件名开头应该是无效的(因此,我的测试将查看不同的字符)
循环并重命名代码
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
正则表达式功能替代
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句