【问题标题】:VBA Loop through all files in folder and remove invalid charactersVBA循环遍历文件夹中的所有文件并删除无效字符
【发布时间】:2015-05-14 10:06:23
【问题描述】:

我找到了替换文件名中无效字符的函数。我想将它用于一个文件夹中的所有文件。

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

【问题讨论】:

  • 上面只打印替换后的文件名,实际上并没有重命名文件;它是否正确?再想一想,您将无法创建此类文件;因为 Windows 不允许您创建名称无效的文件。你能解释一下吗?

标签: vba for-loop file-rename invalid-characters


【解决方案1】:

你有一些问题

  • 你的 Dir 循环
  • 实际上并未重命名您检查过的文件名

下面的代码就是这样做的。请更改StrDir 以适应

但我注意到,由于这些字符是非法的,因此文件名一开始就应该是无效的(因此我的测试会查看不同的字符)

循环和重命名代码

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

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多