Stuart McLachlan
stuart at lexacorp.com.pg
Sat Jun 17 04:49:48 CDT 2006
Gustav's solution works for a simple filename, but not filenames including paths. If you are passing a full name, you need to change Const cstrInValidChars As String = "\/:*?""<>|" to Const cstrInValidChars As String = "/*?""<>|" Also, the folllowing loop should be a bit quicker than the original, especially for long path/file names: lngLen = Len(cstrInValidChars) For lngPos = 1 To lngLen strTrim = Replace(strTrim, Mid$(cstrInValidChars, lngPos, 1), cstrReplaceChar) Next On 17 Jun 2006 at 10:49, Gustav Brock wrote: > We use this function to clean user typed file names by replacing such chars > with a dash: > > Function TrimFileName( _ > ByVal strFileName As String) _ > As String > > ' Replaces characters in strFileName that are > ' not allowed by Windows as a file name. > ' Truncates length of strFileName to clngFileNameLen. > ' > ' 2000-12-07. Cactus Data ApS, CPH. > ' 2002-05-22. Replaced string concatenating with Mid(). > > ' No special error handling. > On Error Resume Next > > ' String containing all not allowed characters. > Const cstrInValidChars As String = "\/:*?""<>|" > ' Replace character for not allowed characters. > Const cstrReplaceChar As String * 1 = "-" > ' Maximum length of a file name. > Const clngFileNameLen As Long = 255 > > Dim lngLen As Long > Dim lngPos As Long > Dim strChar As String > Dim strTrim As String > > ' Strip leading and trailing spaces. > strTrim = Left(Trim(strFileName), clngFileNameLen) > lngLen = Len(strTrim) > For lngPos = 1 To lngLen Step 1 > strChar = Mid(strTrim, lngPos, 1) > If InStr(cstrInValidChars, strChar) > 0 Then > Mid(strTrim, lngPos) = cstrReplaceChar > End If > Next > > TrimFileName = strTrim > > End Function > -- Stuart