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
-
Help with WD usb driver on Windows 11
by
Tex265
27 minutes ago -
hibernate activation
by
e_belmont
1 hour, 17 minutes ago -
Red Hat Enterprise Linux 10 with AI assistant
by
Alex5723
5 hours, 5 minutes ago -
Windows 11 Insider Preview build 26200.5603 released to DEV
by
joep517
8 hours, 9 minutes ago -
Windows 11 Insider Preview build 26120.4151 (24H2) released to BETA
by
joep517
8 hours, 11 minutes ago -
Fixing Windows 24H2 failed KB5058411 install
by
Alex5723
11 hours, 21 minutes ago -
Out of band for Windows 10
by
Susan Bradley
12 hours, 54 minutes ago -
Giving UniGetUi a test run.
by
RetiredGeek
19 hours, 52 minutes ago -
Windows 11 Insider Preview Build 26100.4188 (24H2) released to Release Preview
by
joep517
1 day, 3 hours ago -
Microsoft is now putting quantum encryption in Windows builds
by
Alex5723
1 day, 1 hour ago -
Auto Time Zone Adjustment
by
wadeer
1 day, 7 hours ago -
To download Win 11 Pro 23H2 ISO.
by
Eddieloh
1 day, 5 hours ago -
Manage your browsing experience with Edge
by
Mary Branscombe
10 hours, 13 minutes ago -
Fewer vulnerabilities, larger updates
by
Susan Bradley
21 hours, 9 minutes ago -
Hobbies — There’s free software for that!
by
Deanna McElveen
5 hours, 3 minutes ago -
Apps included with macOS
by
Will Fastie
2 hours, 55 minutes ago -
Xfinity home internet
by
MrJimPhelps
1 day ago -
Convert PowerPoint presentation to Impress
by
RetiredGeek
1 day ago -
Debian 12.11 released
by
Alex5723
2 days, 5 hours ago -
Microsoft: Troubleshoot problems updating Windows
by
Alex5723
2 days, 8 hours ago -
Woman Files for Divorce After ChatGPT “Reads” Husband’s Coffee Cup
by
Alex5723
1 day, 12 hours ago -
Moving fwd, Win 11 Pro,, which is best? Lenovo refurb
by
Deo
40 minutes ago -
DBOS Advanced Network Analysis
by
Kathy Stevens
3 days, 1 hour ago -
Microsoft Edge Launching Automatically?
by
healeyinpa
2 days, 16 hours ago -
Google Chrome to block admin-level browser launches for better security
by
Alex5723
13 hours, 50 minutes ago -
iPhone SE2 Stolen Device Protection
by
Rick Corbett
2 days, 20 hours ago -
Some advice for managing my wireless internet gateway
by
LHiggins
2 days, 4 hours ago -
NO POWER IN KEYBOARD OR MOUSE
by
HE48AEEXX77WEN4Edbtm
1 day, 6 hours ago -
A CVE-MITRE-CISA-CNA Extravaganza
by
Nibbled To Death By Ducks
3 days, 13 hours ago -
Sometimes I wonder about these bots
by
Susan Bradley
1 day, 1 hour 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.