Does anybody have a snippet of code that will test if a string would be invalid as a filename. I have an Access app that uses a user-defined string as part of the filename for a printed report. I need to test for and prohibit a user from using invalid filename characters. I appreciate any input here. Thanks
![]() |
Patch reliability is unclear. Unless you have an immediate, pressing need to install a specific patch, don't do it. |
SIGN IN | Not a member? | REGISTER | PLUS MEMBERSHIP |
-
Invalid Charaters (VBA)
Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Invalid Charaters (VBA)
- This topic has 9 replies, 6 voices, and was last updated 21 years ago.
Viewing 8 reply threadsAuthorReplies-
WSJohnBF
AskWoody LoungerMay 24, 2004 at 5:03 pm #832067Not exactly, but I have this old generic function that I use to strip out specified invalid file name characters without asking the user:
Function StripTheseChars(ByVal strInput As String, _
ByVal strChars2Del As String) As String
Dim lngPos As Long, lngInputSLen As Long, lngDelCharsLen As Long, lngCounter As Long
Dim strCurrentChar2Del As String
lngDelCharsLen = Len(strChars2Del)
For lngCounter = 1 To lngDelCharsLen
strCurrentChar2Del = Mid(strChars2Del, lngCounter, 1)
DWhile InStr(strInput, strCurrentChar2Del)
lngInputSLen = Len(strInput)
lngPos = InStr(strInput, strCurrentChar2Del)
strInput = Left(strInput, lngPos – 1) & Right(strInput, lngInputSLen – lngPos)
Loop
Next lngCounter
StripTheseChars = strInput
End Functioncalled like this
strSuggestFN = StripTheseChars(strSuggestFN, ” .*,|/()[]{}”””)I think it’s coded for VB5, it could probably be simpler in VB6.
-
WSjscher2000
AskWoody LoungerMay 24, 2004 at 7:23 pm #832163This is some old VBScript, but it looks as though the VBA would be identical in this case:
Do strTemp = InputBox("[Instructions to user]", _ "Enter your information here!", strDefault) If Len(Trim(strTemp)) = 0 Then If MsgBox("Do you want to skip this directory after all?", 4+32) = 6 Then getInput = "*SKIPDIRECTORY*" Exit Function Else MsgBox "Please re-enter the prefix you want to add to the file names." End If Else 'some minimal validation for illegal characters If (InStr(1, strTemp, "/") > 0) Or (InStr(1, strTemp, "") > 0) Or _ (InStr(1, strTemp, "*") > 0) Or (InStr(1, strTemp, "?") > 0) Or _ (InStr(1, strTemp, "|") > 0) Or (InStr(1, strTemp, """") > 0) Or _ (InStr(1, strTemp, " 0) Or (InStr(1, strTemp, ">") > 0) Or _ (InStr(1, strTemp, ":") > 0) Then MsgBox "Please revise the prefix so it does not contain illegal characters." Else getInput = strTemp Exit Do End If End If Loop
Hope this helps.
-
WSjscher2000
AskWoody LoungerMay 24, 2004 at 7:23 pm #832164This is some old VBScript, but it looks as though the VBA would be identical in this case:
Do strTemp = InputBox("[Instructions to user]", _ "Enter your information here!", strDefault) If Len(Trim(strTemp)) = 0 Then If MsgBox("Do you want to skip this directory after all?", 4+32) = 6 Then getInput = "*SKIPDIRECTORY*" Exit Function Else MsgBox "Please re-enter the prefix you want to add to the file names." End If Else 'some minimal validation for illegal characters If (InStr(1, strTemp, "/") > 0) Or (InStr(1, strTemp, "") > 0) Or _ (InStr(1, strTemp, "*") > 0) Or (InStr(1, strTemp, "?") > 0) Or _ (InStr(1, strTemp, "|") > 0) Or (InStr(1, strTemp, """") > 0) Or _ (InStr(1, strTemp, " 0) Or (InStr(1, strTemp, ">") > 0) Or _ (InStr(1, strTemp, ":") > 0) Then MsgBox "Please revise the prefix so it does not contain illegal characters." Else getInput = strTemp Exit Do End If End If Loop
Hope this helps.
-
WSAndrew Cronnolly
AskWoody LoungerMay 24, 2004 at 8:33 pm #832198This is along the lines of John’s suggestion, but for Office 2000 VBA or later.
Function CleanFileName(strFileName As String) As String
Dim Invalids, e, strTemp As String
Invalids = Array(“?”, “*”, “:”, “|”, “”, “[“, “]”, “”, “/”)
strTemp = strFileName
For Each e In Invalids
strTemp = Replace(strTemp, e, “”)
Next
CleanFileName = strTemp
End FunctionAny or all characters in the Invalids array are stripped from the string passed to the function.
Andrew C
-
WSAndrew Cronnolly
AskWoody LoungerMay 24, 2004 at 8:33 pm #832199This is along the lines of John’s suggestion, but for Office 2000 VBA or later.
Function CleanFileName(strFileName As String) As String
Dim Invalids, e, strTemp As String
Invalids = Array(“?”, “*”, “:”, “|”, “”, “[“, “]”, “”, “/”)
strTemp = strFileName
For Each e In Invalids
strTemp = Replace(strTemp, e, “”)
Next
CleanFileName = strTemp
End FunctionAny or all characters in the Invalids array are stripped from the string passed to the function.
Andrew C
-
WSAndrew77
AskWoody Lounger -
WSAndrew77
AskWoody Lounger -
WSMarkD
AskWoody LoungerMay 25, 2004 at 2:47 am #832287Here is yet another example, with option to replace invalid character with another character of your (not user’s) choosing. This takes into account that although periods are “legal” characters, a filename cannot consist of only periods (or, for that matter, an empty string); and that Windows will truncate any trailing periods not followed by another character or characters. StrConv function is used to convert string to and from an array of bytes. Code:
Public Function IsFileNameValid(ByRef strFileSpec As String, _
ByRef bReplace As Boolean, _
Optional ReplaceWith As String = “_”) As Boolean
On Error GoTo Err_HandlerDim strMsg As String
Dim b() As Byte
Dim n As LongIsFileNameValid = True
‘ Invalid FileName characters (XP):
‘ 92 / 47 : 58 * 42 ? 63 ” 34 62 | 124‘ Trailing periods removed from file name:
If Len(Trim$(Replace(strFileSpec, “.”, vbNullString, , , vbBinaryCompare))) > 0 Then
‘ Remove any trailing periods:
Do Until Right$(strFileSpec, 1) “.”
strFileSpec = Left$(strFileSpec, Len(strFileSpec) – 1)
Loop‘ Convert string to byte array:
b = StrConv(strFileSpec, vbFromUnicode)
For n = 0 To UBound(
Select Case b(n)
Case 34, 42, 47, 58, 60, 62, 63, 92, 124
IsFileNameValid = False
If bReplace Then
‘ Asc function evaluates 1st char only:
b(n) = Asc(ReplaceWith)
Else
‘ Not replacing character:
Exit For
End If
Case Else
‘ OK
End Select
Next
Else
IsFileNameValid = False
End If‘ Optional – convert input string back to Unicode text (passed by ref):
If bReplace Then
strFileSpec = StrConv(b, vbUnicode)
Debug.Print strFileSpec
End IfExit_Sub:
Exit Function
Err_Handler:
strMsg = “Error No ” & Err.Number & “: ” & Err.Description
MsgBox strMsg, vbExclamation, “IS FILENAME VALID FUNCTION ERROR”
Resume Exit_Sub
End FunctionSample results:
? IsFileNameValid(“ABC…”,True)
ABC
True? IsFileNameValid(“ABC?.d*c”,True)
ABC_.d_c
False? IsFileNameValid(“”,True,”%”)
%htm.doc%
FalseNote that AFAIK, brackets in filename are “legal”, while double-quotes (“) are not (at least in XP – see attached pic).
HTH
-
WSMarkD
AskWoody LoungerMay 25, 2004 at 2:47 am #832288Here is yet another example, with option to replace invalid character with another character of your (not user’s) choosing. This takes into account that although periods are “legal” characters, a filename cannot consist of only periods (or, for that matter, an empty string); and that Windows will truncate any trailing periods not followed by another character or characters. StrConv function is used to convert string to and from an array of bytes. Code:
Public Function IsFileNameValid(ByRef strFileSpec As String, _
ByRef bReplace As Boolean, _
Optional ReplaceWith As String = “_”) As Boolean
On Error GoTo Err_HandlerDim strMsg As String
Dim b() As Byte
Dim n As LongIsFileNameValid = True
‘ Invalid FileName characters (XP):
‘ 92 / 47 : 58 * 42 ? 63 ” 34 62 | 124‘ Trailing periods removed from file name:
If Len(Trim$(Replace(strFileSpec, “.”, vbNullString, , , vbBinaryCompare))) > 0 Then
‘ Remove any trailing periods:
Do Until Right$(strFileSpec, 1) “.”
strFileSpec = Left$(strFileSpec, Len(strFileSpec) – 1)
Loop‘ Convert string to byte array:
b = StrConv(strFileSpec, vbFromUnicode)
For n = 0 To UBound(
Select Case b(n)
Case 34, 42, 47, 58, 60, 62, 63, 92, 124
IsFileNameValid = False
If bReplace Then
‘ Asc function evaluates 1st char only:
b(n) = Asc(ReplaceWith)
Else
‘ Not replacing character:
Exit For
End If
Case Else
‘ OK
End Select
Next
Else
IsFileNameValid = False
End If‘ Optional – convert input string back to Unicode text (passed by ref):
If bReplace Then
strFileSpec = StrConv(b, vbUnicode)
Debug.Print strFileSpec
End IfExit_Sub:
Exit Function
Err_Handler:
strMsg = “Error No ” & Err.Number & “: ” & Err.Description
MsgBox strMsg, vbExclamation, “IS FILENAME VALID FUNCTION ERROR”
Resume Exit_Sub
End FunctionSample results:
? IsFileNameValid(“ABC…”,True)
ABC
True? IsFileNameValid(“ABC?.d*c”,True)
ABC_.d_c
False? IsFileNameValid(“”,True,”%”)
%htm.doc%
FalseNote that AFAIK, brackets in filename are “legal”, while double-quotes (“) are not (at least in XP – see attached pic).
HTH
Viewing 8 reply threads -

Plus Membership
Donations from Plus members keep this site going. You can identify the people who support AskWoody by the Plus badge on their avatars.
AskWoody Plus members not only get access to all of the contents of this site -- including Susan Bradley's frequently updated Patch Watch listing -- they also receive weekly AskWoody Plus Newsletters (formerly Windows Secrets Newsletter) and AskWoody Plus Alerts, emails when there are important breaking developments.
Get Plus!
Welcome to our unique respite from the madness.
It's easy to post questions about Windows 11, Windows 10, Win8.1, Win7, Surface, Office, or browse through our Forums. Post anonymously or register for greater privileges. Keep it civil, please: Decorous Lounge rules strictly enforced. Questions? Contact Customer Support.
Search Newsletters
Search Forums
View the Forum
Search for Topics
Recent Topics
-
AMD : Out of Bounds (OOB) read vulnerability in TPM 2.0 CVE-2025-2884
by
Alex5723
4 hours, 36 minutes ago -
Totally remove or disable BitLocker
by
CWBillow
3 hours, 29 minutes ago -
Windows 10 gets 6 years of ESU?
by
n0ads
19 minutes ago -
Apple, Google stores still offer China-based VPNs, report says
by
Nibbled To Death By Ducks
15 hours, 22 minutes ago -
Search Forums only bring up my posts?
by
Deo
15 hours, 36 minutes ago -
Windows Spotlight broken on Enterprise and Pro for Workstations?
by
steeviebops
1 day, 3 hours ago -
Denmark wants to dump Microsoft for Linux + LibreOffice
by
Alex5723
19 hours, 41 minutes ago -
How to get Microsoft Defender to honor Group Policy Setting
by
Ralph
1 day, 3 hours ago -
Apple : Paragon’s iOS Mercenary Spyware Finds Journalists Target
by
Alex5723
1 day, 13 hours ago -
Music : The Rose Room – It’s Been A Long, Long Time album
by
Alex5723
1 day, 14 hours ago -
Disengage Bitlocker
by
CWBillow
1 day, 4 hours ago -
Mac Mini M2 Service Program for No Power Issue
by
Alex5723
1 day, 16 hours ago -
New Win 11 Pro Geekom Setup questions
by
Deo
15 hours, 31 minutes ago -
Windows 11 Insider Preview build 26200.5651 released to DEV
by
joep517
2 days ago -
Windows 11 Insider Preview build 26120.4441 (24H2) released to BETA
by
joep517
2 days ago -
iOS 26,, MacOS 26 : Create your own AI chatbot
by
Alex5723
2 days, 4 hours ago -
New PC transfer program recommendations?
by
DaveBoston
9 hours, 2 minutes ago -
Windows 11 Insider Preview Build 22631.5545 (23H2) released to Release Preview
by
joep517
2 days, 8 hours ago -
Windows 10 Build 19045.6029 (22H2) to Release Preview Channel
by
joep517
2 days, 8 hours ago -
Best tools for upgrading a Windows 10 to an 11
by
Susan Bradley
1 day, 20 hours ago -
The end of Windows 10 is approaching, consider Linux and LibreOffice
by
Alex5723
1 day ago -
Extended Windows Built-in Disk Cleanup Utility
by
bbearren
1 day, 9 hours ago -
Win 11 24H2 June 2025 Update breaks WIFI
by
dportenlanger
3 days, 3 hours ago -
Update from WinPro 10 v. 1511 on T460p?
by
CatoRenasci
2 days, 1 hour ago -
System Restore and Updates Paused
by
veteran
3 days, 5 hours ago -
Windows 10/11 clock app
by
Kathy Stevens
2 days, 16 hours ago -
Turn off right-click draw
by
Charles Billow
3 days, 8 hours ago -
Introducing ChromeOS M137 to The Stable Channel
by
Alex5723
3 days, 12 hours ago -
Brian Wilson (The Beach Boys) R.I.P
by
Alex5723
52 minutes ago -
Master patch listing for June 10, 2025
by
Susan Bradley
3 days, 14 hours ago
Recent blog posts
Key Links
Want to Advertise in the free newsletter? How about a gift subscription in honor of a birthday? Send an email to sb@askwoody.com to ask how.
Mastodon profile for DefConPatch
Mastodon profile for AskWoody
Home • About • FAQ • Posts & Privacy • Forums • My Account
Register • Free Newsletter • Plus Membership • Gift Certificates • MS-DEFCON Alerts
Copyright ©2004-2025 by AskWoody Tech LLC. All Rights Reserved.