用于新文件夹字符的VBA Excelmacros的正则expression式

我有一个布尔函数,并返回是否可以根据它的值或不创build一个新的文件夹的单元格(如果它拥有以下字符:<,>,|,\,*,?)

但是从一些奇怪的原因来看,它总是返回假,或者是一个单元格。 所以,我有一个为所有行创build循环的子文件,并创build一些.txt文件并将其放入自动生成的文件夹中。

这是我的代码:

Sub CreateTxtSrb() Dim iRow As Long Dim iFile As Integer Dim sPath As String Dim sFile As String Dim iEnd As Range 'iEnd = Cells(Rows.Count, "B").End(xlUp).Row For iRow = 1 To Cells(Rows.Count, "B").End(xlUp).Row iFile = FreeFile With Rows(iRow) If IsValidFolderName(.Range("B2").Value) = False Or IsValidFolderName(.Range("D2").Value) = False Or IsValidFolderName(.Range("F2").Value) = False Then MsgBox ("Check columns B,D or F, it cannot contains chars: <,>,?,|,\,/,*,. or a space at the end") Exit Sub Else strShort = IIf(InStr(.Range("E2").Value, vbCrLf), Left(.Range("E2").Value, InStr(.Range("E2").Value, vbCrLf) - 2), .Range("E2").Value) sPath = "E:\" & .Range("B2").Value & "\" If Len(Dir(sPath, vbDirectory)) = 0 Then MkDir sPath sFile = .Range("D2").Value & ".txt" Open sPath & sFile For Output As #iFile Print #iFile, .Range("E2").Value Close #iFile End If End With Next iRow End Sub Function IsValidFolderName(ByVal sFolderName As String) As Boolean 'http://msdn.microsoft.com/en- us/library/windows/desktop/aa365247(v=vs.85).aspx#file_and_directory_names 'http://msdn.microsoft.com/en-us/library/ie/ms974570.aspx On Error GoTo Error_Handler Dim oRegEx As Object 'Check to see if any illegal characters have been used Set oRegEx = CreateObject("vbscript.regexp") oRegEx.Pattern = "[&lt;&gt;:""/\\\|\?\*]" IsValidFolderName = Not oRegEx.test(sFolderName) 'Ensure the folder name does end with a . or a blank space If Right(sFolderName, 1) = "." Then IsValidFolderName = False If Right(sFolderName, 1) = " " Then IsValidFolderName = False Error_Handler_Exit: On Error Resume Next Set oRegEx = Nothing Exit Function Error_Handler: MsgBox ("test") ' MsgBox "The following error has occurred" &amp; vbCrLf &amp; vbCrLf &amp; _ ' "Error Number: " &amp; Err.Number &amp; vbCrLf &amp; vbCrLf &amp; _ ' "Error Source: IsInvalidFolderName" &amp; vbCrLf &amp; _ ' "Error Description: " &amp; Err.Description, _ ' vbCritical, "An Error has Occurred!" Resume Error_Handler_Exit End Function 

如果需要的话,我怎样才能使它恢复正确?

你不需要外部参考你可以简单地:

 hasInvalidChars = sFolderName like "*[<>|\/:*?""]*" 

我添加了":这也是非法的。

(在你的例子中你有HTML实体(例如&lt; ) – 这些在你的RegExstring中没有意义,并且在类中被解释为4个字符)

这是一团糟。 使用一个单独的function

 Public Function IsInvalid(ByVal name As String) As Boolean Dim regex As Object Set regex = VBA.CreateObject("VBScript.RegExp") regex.Pattern = "[\\/:\*\?""<>\|]" 'the disallowed characters IsInvalid = (regex.Execute(name).Count > 0) End Function 

相反,并在适当时调用它。