Strings and Manipulations
Location:   http://www.mvps.org/dmcritchie/excel/strings.htm
Home page: http://www.mvps.org/dmcritchie/excel/excel.htm
[View without Frames]

Text Functions, Workbook
Before continuing please be aware of the following information available in Excel HELP

FIND(find_text,within_text,start_num)
Worksheet Description VBA   
CHAR Returns the character specified by the code number CHR
CLEAN Removes all nonprintable characters from text
Characters 0-31, 129, 141, 143, 144, and 157
CLEAN
CODE Returns a numeric code for the first character in a text string
If Asc("x") = y  is faster than  If Chr$(y) = "x"
ASC
CONCATENATE  Joins several text items into one text item & or +
DOLLAR Converts a number to text, using currency format (none)
EXACT Checks to see if two text values are identical (case sensitive) =
FIND Finds one text value within another (case sensitive), also see SEARCH InStr
  [Excel]: FIND(needle,haystack,start_num)  
  [VBA]: longval = Instr([start, ]haystack,needle], compare]) -- compare = 0 for binary  
FIXED Formats a number as text with a fixed number of decimals ???
ISBLANK Refers to an Empty Cell, Function returns True or False ISEMPTY
LEFT Returns the leftmost characters from a text value LEFT
LEN Returns the number of characters in a text string LEN
LOWER Converts text to lowercase LCase
MID Returns a specific number of characters from a text string starting at the position you specify
In VBA the third parameter is optional; the MID Worksheet Function requires all three parameters.
MID, InStr
PROPER Capitalizes the first letter in each word of a text value PROPER
REPLACE Replaces characters within text
In VBA prior to Excel 2K use application.Substitute
REPLACE
Application.Substitute
REPT Repeats text a given number of times REPT
(reverse) Reverses a character string (User Defined Function available) strReverse
RIGHT Returns the rightmost characters from a text value RIGHT
SEARCH Finds one text value within another (not case sensitive), also see FIND InStr
  [VBA]: longval = Instr([start, ]haystack,needle[, compare]) -- compare = 1 for text comparison  
SUBSTITUTE Substitutes new text for old text in a text string (case sensitive) Application.Substitute
T Converts its arguments to text, =T("00123"), into Excel as text CStr
TEXT Formats a number and converts it to text FORMAT
TRIM Removes spaces from text
WS Function remove duplicate inner spaces, both and WS function remove leading and trailing spaces.
TRIM,ltrim, rtrim
UPPER Converts text to uppercase UCase
VALUE Converts a text argument to a number (none)
  (VBA only) Extracts leading digits ignoring embedded spaces. VAL

Listed by Tom Ogilvy from HELP (VBA HELP), but I can't find which help.

Action Keywords
Compare two strings. StrComp
Convert strings. StrConv
Convert to lowercase or uppercase. Format, LCase, UCase
Create string of repeating character. Space, String
Find length of a string. Len
Format a string. Format
Justify a string. LSet, RSet
Manipulate strings. InStr, Left, LTrim, Mid, Right, RTrim, Trim
Set string comparison rules. Option Compare
Work with ASCII and ANSI values. Asc, Chr

For more information on equivalent worksheet function and Visual Basic code. 

HELP (F1) --> Answer Wizard: visual worksheet
    Programming and Language Reference
      Using Microsoft Excel worksheet functions in Visual Basic
      List of Worksheet Functions available to Visual Basic.     [from VBA HELP] [L]

Functions: To use an Excel function in VBA prefix with Application.WorksheetFunction. --
   answer = application.substitute(haystack, needle, replacement)
 c = Len(v) - Len(Application.WorksheetFunction.Substitute(v, ".", ""))

   c = Len(v) - Len(Replace(v, ".", "")) '-- replace function avail in VBA

Not strings but to use some worksheet functions like MIN, MAX
  answer = Application.WorksheetFunction.Min(myRange)

Methods:
  Activesheet.Columns("A").Replace(What, Replacement, LookAt, _
        SearchOrder, MatchCase, MatchByte
)   '--replace method
  Set rng = ActiveSheet.UsedRange.Find("ANN") '-- like FIND shortcut (Ctrl+F), not case sensitive [Example]

Case sensitivity (#sensitivity)

In general Worksheet Functions are not case sensitive, and in VBA programming everything that is strictly VBA is case sensitive.

WS Functions:  to make something case sensitive as in Data Validation, change the “Allow” dropdown to Custom, then, assuming the active cell is A1, enter =Exact(A1,UPPER(A1)) to ensure uppercase, or =EXACT(A1,LOWER(A1)), to ensure lowercase, and click the “error alert” tab and create an appropriate error message.  As mentioned in the table at the top, FIND is case sensitive, and SEARCH is not.  SUBSTITUTE(value,to,from) is entirely case sensitive.  UPPER, LOWER, and PROPER are not case sensitive but will convert the letter case.

VBA: usage is case sensitive.  Application. -- invokes an Excel function so it will be case sensitive if the Excel function is case sensitive.  To make VBA not case sensitive you can use UCASE or LCASE as in IF UCASE(myvar) = "ABC" THEN ...
 
There are a few VB functions that can be made case insensitive with an operand (InStr, Sort, Replace, Find, Select)
  InStr(1, Range("b2"), "text")      as binary comparison (default is 0: vbBinaryCompare)
  InStr(1, Range("b2"), "Text", 1)   as textual comparison (1: vbTextCompare)

Check Validity of Data (#debugformat)

Worksheet Functions to determine the actual data content: ISNUMBER, ISTEXT, LEN, ISBLANK, CODE.  (see Debug Format on my Formula page.

Wildcard Characters   (#wildcards   ?, or *, or ~)

The Search Worksheet Function is not case sensitive and allows wildcards, precede wildcard characters of ?, or *, or ~ with a ~ (tilde) to match actual character.  The FIND Worksheet Function (case sensitive) does not allow wildcards.   Wildcards: ? single character, * any number of characters. 

Find (Ctrl+F) and Replace (Ctrl+H) shortcuts are not case sensitive and allow wildcards and overrides of wildcards.

Examples of ”wildcard” use can be found in SEARCH and FIND among some Conditional Formatting examples.

Don't confuse with ampersand(&) formatting text in headers and footers (to type a plain ampersand double them as in AT&&T.

Also read about Regular Expressions and LIKE (VBA Operator).

Concatenation & Quotes (#quotes)

The following are equivalent

To indicate a quote you double the quote within text, so your orginal VBA example could be simplified to.

    msgbox "hello and ""Goodbye"""

William's method can keep things straight if you have several layers of quoted material, 
but I believe he meant to use
    msgbox = "Hello and " & chr(34)& "Goodbye" & chr(34)

Your original would work if you doubled the enclosed quotes:
      msgbox "hello and " & """ & "Goodbye" & """"

On the worksheet the equivalent would include any of the following:
    ="hello and ""Goodbye"""
    ="hello " & char(34) & "Goodbye" & char(34)
    ="hello " & """" & "Goodbye" & """"
    =concatenate("hello ", char(34), "Goodbye", char(34))

Converting Text Data (#convert)

Changing character case to proper, lowercase, or uppercase

programmed VBA functions:
   PROPER(Proper), LOWER (LCase), and UPPER (UCase)  
Note the VBA example for Proper contains extra code to not capitalize the first letter of certain words after the first word.

Worksheet Functions:
   =PROPER(),  =LCASE(), and = UPPER()    

Extract the first two initials (#extract)

Knowing your data is important for this, basically assumes you can obtain two initials.  Though a space has been concatenated to cell A37 in the example to prevent a #VALUE! failure.

=UPPER(LEFT(A37,1)&"."&MID(A37,FIND(" ",A37&" ")+1,1)&". ")

Extract the first word

Extract the first word, contains extra code so it will not display a zero when the source cell is empty, and won't fail if there is only one word in source.

=IF(LEN(A11)=0,"",IF(ISERR(FIND(" ",A11)),A11,LEFT(A11,FIND(" ",A11)-1)))

Extract the portion after space/hyphen/space

Extract the second part defined as after a space-hyphen-space.

=IF(ISERROR(FIND(" - ",A1)),"",MID(A1,FIND(" - ",A1)+3,999))

If find_text does not appear in within_text, FIND and FINDB return the #VALUE! error value.
 
You can also use SEARCH to find one text string within another, but unlike SEARCH, FIND is case sensitive and doesn't allow wildcard characters.

Extract the portion between the Parenthesis or other delimiters

=IF(ISERROR(FIND(")",A1)),"",IF(ISERROR(FIND("(",A1)),"",LEFT(RIGHT(A1,LEN(A1)-FIND("(",A1)),FIND(")",RIGHT(A1,LEN(A1)-FIND("(",A1)))-1)))

Breaking apart the above to visualize:
  Sample data:
    Peachtree Ltd (Boston), L.C. Casey, Manager
 
The following returns “(Boston)” if both parens are present
=RIGHT(A1,LEN(A1)-FIND("(",A1))
The following uses above formula, removing both parens, and checks for ISERROR
=IF(ISERROR(FIND(")",A1)),"",IF(ISERROR(FIND("(",A1)),"",LEFT(F1,FIND(")",F1)-1)))

Find number of characters in a Cell or in a Range   (#countchars)

    WS:   =LEN(A1)
    VBA:  = Len(Rng.Value)

SUBSTITUTE Worksheet Function is case sensitive to make an insensitive comparison both the from and the target must match in case, by using UPPER on the the target, and by using uppercase character within quotes.

Find number of occurrences of a character in a cell     i.e. A1: 'banana
keeping in mind that SUBSTITUTE itself is case sensitive
    =len(a1)-len(substitute(a1,"a",""))     — lettercase must match
    =len(a1)-len(substitute(upper(a1),"A",""))     — insensitive to lettercase, but the case of the from
                        in the argument must match that of the UPPER(target).

Number of Characters including spaces in a cell
    =LEN(A1)
Non blank characters in a cell
    =LEN(SUBSTITUTE(A2," ",""))
Blank characters in a cell
    =LEN(A1)-LEN(SUBSTITUTE(A1," ",""))
Number of cells in a range containing at least one occurence of a character
    =COUNTIF(range,"#") -- Alan Beban 2003-08-29
Number of occurences of a character or string in a range of cells counts muliple occurences within each cell --Tom Ogilvy 2003-08-29
   =SUM(LEN(H16:H19)-LEN(SUBSTITUTE(H16:H19,"#",""))) -- array formula enter with Ctrl+Shift+Enter
   =SUMPRODUCT(LEN(H16:H19)-LEN(SUBSTITUTE(H16:H19,"#",""))) -- normal entry
Number of CAPITAL letters in a cell
   (Dave Peterson, worksheet solution posted in Programming, 2003-04-27)
    =SUM(LEN(A1)-LEN(SUBSTITUTE(A1,CHAR(ROW(INDIRECT("65:90"))),""))) -- array solution
    =SUMPRODUCT(LEN(A1)-LEN(SUBSTITUTE(A1,CHAR(ROW(INDIRECT("65:90"))),""))) -- non array solution
Number of CAPITAL letters in a Range of cells
   (Dave Peterson, worksheet solution posted in Programming, 2003-04-27, array solution)
    =SUM(LEN(A1:A10) -LEN(SUBSTITUTE(A1:A10,TRANSPOSE(CHAR(ROW(INDIRECT("65:90")))),"")))
Number of CAPITAL letters in a cell or Range of cells (revisited)
    Peo Sjoblom 2001-12-25, non array solution
   =SUM(LEN($A$1:$A$50)-(LEN(SUBSTITUTE(UPPER($A$1:$A$50),UPPER(B1),""))))
   use lower in both places to find number of lower case letters.

Additional example appear elsewhere some of the other examples are actually the same as those within this topic, basically you can use a char or a string of characters interchangeably.

Find the number of items separated by commas (#countitems)

Will return 2 if but a single comma, but the main thing was to show zero if the cell is empty or contains only spacs
    =LEN(A1)-LEN(SUBSTITUTE(A1,",",""))+(LEN(TRIM(A1))>0)

Find the nth word in a string (#nthWord)

ExtractElement returns “0133”, which is the fourth element in the string. The string uses a hyphen (-) as the separator in the following example:

  =ExtractElement("123-456-789-0133-8844",4,"-")

Code for ExtractElement at http://www.j-walk.com/ss/excel/tips/tip32.htm

An alternative is Laurent Longre's WMID (part of his free MOREFUNC.XLL add-in, available at http://longre.free.fr/english)

  =TRIM(WMID(A1,1,1,"~"))

There is a website that will help you translate Laurent's French website to English while browsing and using hyperlinks.
    Go translator  [http://translator.go.com/]

Find the last word in a string (#lastword)

Don't ask me how this works it was posted 1998/05/29 by Laurent Longre.  This will find the last word in cell A1.  Works at least in XL95 and XL97.

  =TRIM(CALL("Crtdll","strrchr","CCI",A1,32))

The above does not work in Excel 2000 because CALL was disabled in Excel 2000 and some of the later bug fixes in Excel 97.  In reality if the purpose to to separate names I would have been using a macro such as SepLastTerm() separates last word from beginning of text with the last term being moved to the cell on the right.  The next example provides a means of finding the last word use a space (“ ”) instead of backslash (“\”).

Find the last word in a string (revisited)

Finding the content after the last occurrence of a delimiter.  This solution presented by Ken Wright, 2003-06-26, will work in all versions of Excel.  Note the use of the 3rd parameter of Substitute.  Using a space (" ") instead of backslash ("\") provides the last word in a string. 

  =RIGHT(A1,LEN(A1)-FIND("*",SUBSTITUTE(A1,"\","*",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))

  A B C
1 a\b\c\dd\ee\ffff ffff =RIGHT(A1,LEN(A1)-FIND("*",SUBSTITUTE(A1,"\","*",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))
2   abcddeeffff =SUBSTITUTE(A1,"\","")
3   16 =LEN(A1)
4   11 =LEN(SUBSTITUTE(A1,"\",""))
5   a\b\c\dd\ee*ffff =SUBSTITUTE(A1,"\","*",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))
6   a\b\c\dd\ee*ffff =SUBSTITUTE(A1,"\","*",5)

In VBA use InStrRev (or 188007 - HOWTO: Simulate Visual Basic 6.0 String Functions in VB5)
MsgBox Mid("blah\blah1\blah2\blah3", InStrRev("blah\blah1\blah2\blah3", "\") + 1)

Find the number of words in a string   (#wordcnt)

A worksheet solution:  returns the number of words found in cell A1, where CHAR(32) is a space.  The char(32) is same as a hex code of 20 to some of us, and is less ambiguous than " ", and less likely to be inadvertently modified.
       =IF(LEN(TRIM(A1))=0,0,LEN(TRIM(A1))-LEN(SUBSTITUTE(TRIM(A1),CHAR(32),""))+1)

The above reduces the need for the following which probably can be greatly reduced based on the technique used above.  

Peo Sjoblom simplifies coding to (but this is not quite it because this is incorrect):

=(LEN(A1)-LEN(SUBSTITUTE(UPPER(A1),UPPER("open"),"")))/LEN("open")

WordCount returns 6, which is the number of words in the following example: in the string.  The string uses a space(" ") as the separator in the following example:

  =WordCount("There are six words found here."," ")

Code for WordCount() (This code is derived from ExtractElement coding)

Find the first n words in a string (#1stNwords)

Find the first two words in a string.  The TRIM eliminates leading blanks if any.
     =LEFT(TRIM(A1),(FIND(" ",TRIM(A1)&"   ",FIND(" ",TRIM(A1)&" ")+1)-1))
For what it's worth, there is an LTRIM in VBA, but not in Excel.  Excel will reduce the number of spaces in the middle, so that "A      TWO" would still produce first two words of "A TWO"

Find the nth occurrence of a word in a string, etc. (#nthoccurred)

      No coding yet -- haven't seen use for it yet.

Find the number of occurrences of a string in a single cell (#occurs)

       =(LEN(A1)-LEN(SUBSTITUTE(A1,"aa","")))/LEN("aa")
      -- Jim Rech in worksheet.functions 1999-12-02

      To make the test case insensitive place argument within UPPER(...)
      =(LEN(A1)-LEN(SUBSTITUTE(UPPER(A1),"AA","")))/LEN("AA")

Find the number of cells in a range that have string as their value   (#countif)
      =countif(A1:J1,"aa")     Assuming in row 1, columns A through J.

Find string between two different delimiters (period on left, @ on right)

Strip out McRitchie from David.McRitchie@myispNOSPAM.com

=MID(LEFT(A1,FIND("@",A1)-1),FIND(".",A1)+1,255)

Find String between two similiar delimiters (http:// and /  to the right)

The previous method will not work if the second delimiter is also found earlier.  The following will strip out www.abc.com from http://www.abc.com/... or https://www.abc.com/news/...

=LEFT(MID(B1,FIND("://",B1)+3,255),FIND("/",MID(B1,FIND("://",B1)+3,255))-1)

=IF(A1="","",LEFT(MID(A1,FIND("://",A1)+3,255),FIND("/",MID(A1,FIND("://",A1)+3,255))-1))

First Character checked as alphabetic character

Based on a posted reply by Denny Campbell 1999-02-23

The following returns TRUE if 1st character is a letter and FALSE if it doesn't.
      =NOT(ISNUMBER(VALUE(LEFT(D7,1))))

Modified to reject blank cells meaning ISBLANK (empty, never used), and cells containing only space(s).
      =IF(LEFT(TRIM(D7))="","",NOT(ISNUMBER(VALUE(LEFT(D7,1)))))

Frequency

Return the string that occurs most often: WS:  http://groups.google.com/groups?oi=djq&ic=1&selm=an_313817206
Number of strings in a column:  WS:   =COUNTIF(D1:D50,f2)

Numbers to words (as in check protection wording) (#numberstowords)

Q213360 - XL2000: How to Convert a Numeric Value into English Words in Dollars and Cents
See KB Article Number Q140704   in Dollars and Cents
See KB Article Number Q95640   One Thousand Two Hundred Thirty Four Dollars And Fifty Six Cents

Dollars Function by Bernie Deitrick (works up to trillions) gives you a choice with or without “Dollars and Cents” wording.
  =Dollars(111.11, TRUE) produces One Hundred Eleven Dollars And 11/100
  =Dollars(111.11, FALSE) produces One Hundred Eleven and 11/100

To protect numbers format as:    _($**#,##0.00_);_($**(#,##0.00);_($**"-"??_);_(@_)

Convert numbers to Rupees  MS Excel Macro For Number To Word Conversion
as a macro can be found at http://pun1ww1-a.sancharnet.in:83/akl_valuer/down.htm converts any number upto 999999999.99 into words with Indian currency.  Suggest converting to a User Defined Function.
  =Rupees_as_text(999999999.99) produces
    Rupees Ninety Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred & Ninety Nine - Paise Ninety Nine Only
  =Rupees_as_text(589421) produces
    Rupees Five Lakh Eighty Nine Thousand Four Hundred & Twenty One Only
Also see BHATTEXT available in Excel 2002 or you can simulate in earlier versions.

Convert numbers to Roman numerals  See HELP --> ROMAN worksheet function

Position of First non alphabetic character (#firstnonalpha)

Function Pos_nonalpha(cell) As Integer
  'posted misc 2001-07-23 David McRitchie
  Dim i As Integer
  For i = 1 To Len(cell)
    Dim Number
    Select Case Asc(Mid(cell, i, 1))
        Case 0 To 64, 91 To 96, 123 To 191
           Pos_nonalpha = i
           Exit Function
        End Select
  Next i
  Pos_nonalpha = 0
End Function
Most of 192 to 255 are characters of the Latin1 Font are in other languages with the exceptions of 215 and 247, so you can refine the above to suit your data.  Also see synbols, unicode).

65-90 are uppercase letters, 97-122 are lowercase letters.

Problems with Data, Particularly data pasted from HTML

The following Worksheet Functions can be very useful in determining exactly what you have for your data as Excel sees it -- it may not be what you think it is.  You may have problems with Text and Numbers in a column that you try to sort.  For more information on finding out what the problem with the data is see join.htm#debugformat and for removing CHAR(160) the   or   (non-breaking space in HTML) and extra spaces using a macro see the TRIMALL macro, also read about formulas and formats on my Formulas page.
 
   =ISNUMBER(E2)
   =ISTEXT(E2)
   =LEN(E2)
   =ISBLANK(E2)     [in VBA the equivalent is ISEMPTY]
   =CODE(E2)     =CODE(RIGHT(E2,1))     [in VBA the equivalent is ASC]
   =personal.xls!GetFormula(E2)
   =personal.xls!GetFormat(E2)

String Comparisons, compare to second space   (based on posting 2003-01-090

Formulas include concatenation of two spaces to guarantee finding the second space in each case.
a14:   BA 12345 10-30-2003 must be ---> BA 12345
B14:   NM 12345 AB 40893 Must be ----> NM 12345
D14"  =IF(UPPER(LEFT(A14 & "  ",FIND(" ",RIGHT(A14 & "  ",LEN(A14 & "  ")
            -FIND(" ",A14 & "  ")))+FIND(" ",A14 & "  ")))=
          UPPER(LEFT(B14 & "  ",FIND(" ",RIGHT(B14 & "  ",LEN(B14 & "  ")
            -FIND(" ",B14 & "  ")))+FIND(" ",B14 & "  "))),"Equal","Differs")

or  using a programmed User Defined Function

A14:  BA 12345 x
B14:  BA 1234
C14:  ba 12345   
D14: =CompareTruncate(A14,B14)  -- shows Differs
E14: =CompareTruncate(A14,C14)  -- Equal
 
Function CompareTruncate(ByVal string1 As String, ByVal _
      String2 As String)
    string1 = Left(string1 & "  ", InStr(InStr(string1 & "  ", " ") + 1, _
        string1 & "  ", " "))
    String2 = Left(String2 & "  ", InStr(InStr(String2 & "  ", " ") + 1, _
        String2 & "  ", " "))
    '-- CompareTruncate = UCase(string1) = UCase(String2)--replaced by...
    CompareTruncate = InStr(1, String2, string1, vbTextCompare) = 1
End Function

Return string after last “/” character

Posted on or before 2000-02-19, though still missing (D.McRitchie)
=AFTLAST(E22,"/")

Function AFTLAST(cell As Range, findchar As String) As String
Application.Calculation = xlCalculationManual          'in XL97
For i = Len(cell) To 1 Step -1
    If Mid(cell, i, 1) = findchar Then
        AFTLAST = Mid(cell, i + 1, 99)
        Exit Function
   End If
Next i
AFTLAST = cell   ' or   aftlast=""  depending on what you want
Application.Calculation = xlCalculationAutomatic     'in XL97
End Function

Return string after first “/” character

Remove everything to left of first “/”
    =IF(ISERR(FIND("/",E22)),E22,MID(E22,FIND("/",E22,1)+1,99))
or
    =IF(ISERR(FIND("/",E22)),"",MID(E22,FIND("/",E22,1)+1,99))
depending on whether you want cell value or nothing when "/" is not present.

Rearranging Data in Spreadsheet Columns

Rearrange columns by splitting, joining, or reversing columns of data.
MarkCells()  Creates test data by placing the cells address as the value for each cell in the selected range.

Join columns together
Join() can be used as a reversal of a correctly executed text to columns.

Separate terms across columns
SepTerm() can be used as a more limited version of text to columns that only separates from the first word.

Separate at second term.  First word remains in place, second and remainder go into the next column.  This is accomplished using SepTerm() with a two column range.  The first term will remain and the remainder will go into the second column.

SepLastTerm() separates last word from from beginning of text.

Reverse the order of items in a row, column, or range
ReversI() is used to reverse the order of items in a row, column, or range.


Remove All Spaces (#removespaces)

=SUBSTITUTE(A1," ","")

Removing Unprintable Characters

It would be advisable to find out exactly what the characters are, because you might want to do different things with different “unprintable” characters.  If so you might want to use REPLACE to replace characters with a space, instead of the CLEAN which will remove them.   i.e.   Youmaynotwantitlikethis.

Returns a numeric code for the first character in a text string
Worksheet Function:   =CODE(A1)
VBA:         MsgBox ASC(cell.value)

9 = TAB, 10=LF, 13=CR, 160 is non breaking space ( )
(line feed, carriage return, if both are used CRLF)

Perhaps more on my Symbols page in a different directory: http://www.mvps.org/dmcritchie/rexx/htm/symbols.htm

Just to keep things in perspective:

To find the ASCII code of a single pasted character use CODE(char):
  =CODE("A")   yields 65 for "A", Alt+0065 is "A"
  =CHAR(65)    yields "A" for code 65

Also see the TRIMALL macro and detailed explanations concerning CODE(160) &nbsp (nonbreaking space character), substitutions and removal, along with differences between Excel TRIM and VBA TRIM.


Remove illegal characters from filename   (#filenames)

Function ReplaceIllegalChars(Filename As String) As String
 'leo.heuser@get2net.dk, 5. August 2001, programming
 Dim Illegal As Variant
 Dim Counter As Integer
     Illegal = Array("<", ">", "?", "[", "]", ":", "|", "*", "/")

     For Counter = LBound(Illegal) To UBound(Illegal)
         Do While InStr(Filename, Illegal(Counter))
             Mid(Filename, InStr(Filename, Illegal(Counter)), 1) = "_"
         Loop
     Next Counter
     ReplaceIllegalChars = Filename
 End Function

StrReverse, Reverse Character String   (#strreverse)

Return the string after the last “\”, or the entire string if the back slash is not present.
newString = Mid(yourString, InStrRev(yourString, "\", , vbTextCompare) + 1)
StrReverse was introduced in Excel 2000.  You can write a UDF for use prior to Excel 2000, and if you want to use StrReverse in the worksheet you must use a UDF see strReverse User Defined Function.


The following will probably be removed when topic is completed.

Background for this topic
Subject: VBA String Manipulation Utilities
From: "Joe Latone" <latone@sphinx.com>
Date: Mon, 5 Oct 1998 09:02:45 -0700
Newsgroups: microsoft.public.excel.programming

Is there a repository of VBA string manipulation functions
around somewhere?  E.g., find the nth word in a string,
find the number of words in a string, find the nth occurance
of a word in a string, etc.  I'll write my own if not, but these are
such common, handy routines, I figured there might be a standard
library that everyone uses.  Thanks, Joe

Subject: Re: VBA String Manipulation Utilities
From: “John Walkenbach” <john@j-walk.com>
Date: Mon, 05 Oct 1998 17:04:46 GMT
I don't know of any repository, but the ExtractElement function at my web may be helpful:

  http://www.j-walk.com/ss/excel/tips/tip32.htm

Subject: Re: VBA String Manipulation Utilities
From: MyrnaLarson_nospam@csi.com (Myrna Larson)
Date: Mon, 05 Oct 1998 22:23:30 GMT

The book “VBA Developer's Handbook”, by Getz and Gilbert, ISBN 0-7821-1951-4, $50, has routines for these kinds of things.


A compact list of Worksheet Functions (overview) can be found as
Origin of Excel Worksheet Function Names -- http://www2.odn.ne.jp/excel/functioninenglish.html« by Janma,
the rest of his Excel site, “Excel Skill Training Hall”, is in Japanese.
A reference of Worksheet Functions to definitely download and maintain on your computer
Excel Function Dictionary -- http://homepage.ntlworld.com/noneley « by Peter Noneley,
Alternative download site http://homepage.ntlworld.com/peter.noneley)
workbook with 157+ sheets, each with an explanation and example of an Excel function.  /\
Newsgroups and Searching Newsgroups, Excel
Some information on searching for information using Google Usenet Advanced Search Excel Newsgroups, and some information on searching the Microsoft Knowledge Database (KB).
ExtractDigits, User Defined Function,
extract first set of consecutive digits from a string.  Treat as a number if found as an empty string if none found (i.e., g25abc16 would return 25).  In the next posting in the same thread George Simms extracts set of digits from the leftmost postition only using an array formula (ctrl+shift+enter), but it fails for anything else (i.e. g25abc16 would fail).
=MID(A1,1,MATCH(TRUE,ISERROR(1*MID(A1,ROW(INDIRECT("1:25")),1)),0)-1)*1
Followed by a posting after by Peo Sjoblom an array formula extracts a set of digits as a string from left/middle/right, but it fails if you have two sets of digits or no digits in the same string (i.e. g25abc16 would fail).
=MID(A1,MATCH(FALSE,ISERROR(1*MID(A1,ROW(INDIRECT("1:100")),1)),0),100-SUM(1*ISERROR(1*MID(A1,ROW(INDIRECT("1:100")),1))))*1
Extraction of a Group of Digits and Dashes, posted by Harlan Grove,
use of Regular Expressions (RegExpr) in LIKE within VBA.
Proper, and other Text changes
PROPER, LOWER (LCase), and UPPER (UCase) functions.  TrimSUB subroutine to TRIM cells in a selection.
Rearranging Data in Columns.
Rearrange columns by splitting, joining, or reversing columns of data.  Join() can be used as a reversal of a correctly executed text to columns.  Lastname() can be used as a put lastname first is not already done.  SepTerm() can be used as a more limited version of text to columns that only separates from the first word. SepLastTerm() separates last word from from beginning of text.  ReversI() is used to reverse the order of items in a row, column, or range.  RotateCW() is used to rotate a range of cells 90 degrees preserving formulas and formats.  Selection area must include cell A1.  MarkCells() is used to create test data within the invoked range.  MarkSepAreas() includes cell address and area number for creating test data across multiple ranges.  i.e. A1-1, B1-1, B2-2,C2-2,D2-2.  Additional material includes use of fill handle and creating a sheet with short cut keys for reference.
WordCount
Code for WordCount() was derived from ExtractElement coding.

You are one of many distinguished visitors who have visited my site here or in a previous location  since this page was created on October 6, 1998. 

Visit [my Excel home page]   [Index page]   [Excel Onsite Search]   [top of this page]

Please send your comments concerning this web page to: David McRitchie send email comments


Copyright © 1997 - 2004,  F. David McRitchie,  All Rights Reserved