This function seems to do the same thing that WordPress does when it converts the post’s title into a url. That is, it makes all valid characters lowercase, removes invalid characters, and converts spaces into dashes (or whatever you call Chr$(45)).
It’s all part of an ill-advised attempt at using Excel to make WordPress posts.
The function uses a For Next loop to loop through each character of a string. The ASCII equivalent of the string is tested in a Select Case block. The absence of a Case Else
line is what excludes the bad characters.
Function CleanPostName(ByVal sPostName As String, _
Optional ByVal bCreateURL As Boolean = False) As String
Dim idx As Long
Dim sNew As String
For idx = 1 To Len(sPostName)
Select Case Asc(Mid$(sPostName, idx, 1))
Case 48 To 57 ‘leave numbers
sNew = sNew & Mid$(sPostName, idx, 1)
Case 65 To 90, 97 To 122 ‘convert letters to lowercase
sNew = sNew & LCase$(Mid$(sPostName, idx, 1))
Case 45 ‘leave dashes – no two dashes
If idx > 1 And Right$(sNew, 1) <> Chr$(45) Then
sNew = sNew & Mid$(sPostName, idx, 1)
End If
Case 32 ‘convert spaces to dashes – multiple spaces = one dash
If idx > 1 And Right$(sNew, 1) <> Chr$(45) Then
sNew = sNew & Chr$(45)
End If
End Select
Next idx
If bCreateURL Then
sNew = “http://www.paragonconstructioninc.com/projects/” & sNew & “/”
End If
CleanPostName = sNew
End Function
Optional ByVal bCreateURL As Boolean = False) As String
Dim idx As Long
Dim sNew As String
For idx = 1 To Len(sPostName)
Select Case Asc(Mid$(sPostName, idx, 1))
Case 48 To 57 ‘leave numbers
sNew = sNew & Mid$(sPostName, idx, 1)
Case 65 To 90, 97 To 122 ‘convert letters to lowercase
sNew = sNew & LCase$(Mid$(sPostName, idx, 1))
Case 45 ‘leave dashes – no two dashes
If idx > 1 And Right$(sNew, 1) <> Chr$(45) Then
sNew = sNew & Mid$(sPostName, idx, 1)
End If
Case 32 ‘convert spaces to dashes – multiple spaces = one dash
If idx > 1 And Right$(sNew, 1) <> Chr$(45) Then
sNew = sNew & Chr$(45)
End If
End Select
Next idx
If bCreateURL Then
sNew = “http://www.paragonconstructioninc.com/projects/” & sNew & “/”
End If
CleanPostName = sNew
End Function
Update: Code updated to include numbers and eliminate double dashes.
Posting code? Use <pre> tags for VBA and <code> tags for inline.