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, but widespread attacks make patching prudent. Go ahead and patch, but watch out for potential problems. |
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 20 years, 11 months 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
-
Windows 10 finally gets fix
by
Susan Bradley
4 hours, 25 minutes ago -
AMD Ryzen™ Chipset Driver Release Notes 7.04.09.545
by
Alex5723
5 hours, 45 minutes ago -
Win 7 MS Essentials suddenly not showing number of items scanned.
by
Oldtimer
18 minutes ago -
France : A law requiring messaging apps to implement a backdoor ..
by
Alex5723
18 hours, 49 minutes ago -
Dev runs Windows 11 ARM on an iPad Air M2
by
Alex5723
19 hours, 38 minutes ago -
MS-DEFCON 3: Cleanup time
by
Susan Bradley
9 hours, 38 minutes ago -
KB5056686 (.NET v8.0.15) Delivered Twice in April 2025
by
lmacri
15 hours, 3 minutes ago -
How to enable Extended Security Maintenance on Ubuntu 20.04 LTS before it dies
by
Alex5723
1 day, 6 hours ago -
Windows 11 Insider Preview build 26200.5562 released to DEV
by
joep517
1 day, 10 hours ago -
Windows 11 Insider Preview build 26120.3872 (24H2) released to BETA
by
joep517
1 day, 10 hours ago -
Unable to eject external hard drives
by
Robertos42
1 hour, 33 minutes ago -
Saying goodbye to not-so-great technology
by
Susan Bradley
10 hours, 38 minutes ago -
Tech I don’t miss, and some I do
by
Will Fastie
15 hours, 55 minutes ago -
Synology limits hard drives
by
Susan Bradley
2 days, 15 hours ago -
Links from Microsoft 365 and from WhatsApp not working
by
rog7
1 day, 17 hours ago -
WhatsApp Security Advisories CVE-2025-30401
by
Alex5723
2 days, 21 hours ago -
Upgrade Sequence
by
doneager
2 days, 14 hours ago -
Chrome extensions with 6 million installs have hidden tracking code
by
Nibbled To Death By Ducks
20 hours, 3 minutes ago -
Uninstall “New Outlook” before installing 2024 Home & Business?
by
Tex265
1 day, 13 hours ago -
The incredible shrinking desktop icons
by
Thumper
3 days, 18 hours ago -
Windows 11 Insider Preview Build 22635.520 (23H2) released to BETA
by
joep517
3 days, 19 hours ago -
Connecting hard drive on USB 3.2 freezes File Explorer & Disk Management
by
WSJMGatehouse
18 hours, 48 minutes ago -
Shellbag Analyser & Cleaner Update
by
Microfix
12 hours, 19 minutes ago -
CISA warns of increased breach risks following Oracle Cloud leak
by
Nibbled To Death By Ducks
4 days, 5 hours ago -
Outlook 2024 two sent from email addresses
by
Kathy Stevens
3 days, 9 hours ago -
Speeding up 11’s search
by
Susan Bradley
1 day, 17 hours ago -
HP Pavilion Will Not Wake Up After Being Idle for Longer Period
by
WSwalterwood44
2 days, 5 hours ago -
Make a Windows 11 Local Account Passwordless
by
Drcard:))
4 days, 19 hours ago -
Ubuntu 25.04 (Plucky Puffin)
by
Alex5723
5 days, 2 hours ago -
24H2 fixed??
by
CWBillow
3 days, 19 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.