Excel vba for string

Return to VBA Code Examples

In this Article

  • Loop Through Each Character in a String
  • Loop Through Each Character in a String – Alternative
  • Read Every Word in a String
  • VBA Coding Made Easy

This tutorial will demonstrate how to loop through a string using VBA.

You can perform logic on, or return individual characters from a string in VBA by looping through the string.

Loop Through Each Character in a String

The following is an example of looping through a string using a For…Next Loop, and returning each character in a msgbox.

Sub LoopThroughString()

Dim Counter As Integer
Dim MyString As String

MyString = "AutomateExcel" 'define string

For Counter = 1 To Len(MyString)
    'do something to each character in string
    'here we'll msgbox each character
    MsgBox Mid(MyString, Counter, 1)
Next

End Sub

The Len Function counts the total number of characters in the string. So the expression

For Counter = 1 to Len(MyString

will loop through each letter in the string.

Loop Through Each Character in a String – Alternative

Read Every Character in a String
This example reads every character in a string from left to right and returns the result in a message box. It makes use of the Mid Function.

Sub LoopThroughString()

Dim LookInHere As String
Dim Counter As Integer

'Use your own text here
LookInHere = "AutomateExcel.com"

For Counter = 1 To Len(LookInHere)
    MsgBox Mid(LookInHere, Counter, 1)
Next

End Sub

Read Every Word in a String

This example reads every word in a string from left to right and returns the result in a message box. It makes use of the Split Function.

Sub LoopThroughString2()

Dim LookInHere As String
Dim Counter As Integer
Dim SplitCatcher As Variant

'Use your own text here

LookInHere = "I Heart AutomateExcel.com"

SplitCatcher = Split(LookInHere, " ")

For Counter = 0 To UBound(SplitCatcher)
    MsgBox SplitCatcher(Counter)
Next

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

<<Return to VBA Examples

Quick Guide to String Functions

String operations Function(s)
Append two or more strings Format or «&»
Build a string from an array Join
Compare — normal StrComp or «=»
Compare — pattern Like
Convert to a string CStr, Str
Convert string to date Simple: CDate
Advanced: Format
Convert string to number Simple: CLng, CInt, CDbl, Val
Advanced: Format
Convert to unicode, wide, narrow StrConv
Convert to upper/lower case StrConv, UCase, LCase
Extract part of a string Left, Right, Mid
Format a string Format
Find characters in a string InStr, InStrRev
Generate a string String
Get length of a string Len
Remove blanks LTrim, RTrim, Trim
Replace part of a string Replace
Reverse a string StrReverse
Parse string to array Split

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba strings video

Introduction

Using strings is a very important part of VBA. There are many types of manipulation you may wish to do with strings. These include tasks such as

  • extracting part of a string
  • comparing strings
  • converting numbers to a string
  • formatting a date to include weekday
  • finding a character in a string
  • removing blanks
  • parsing to an array
  • and so on

The good news is that VBA contains plenty of functions to help you perform these tasks with ease.

This post provides an in-depth guide to using string in VBA. It explains strings in simple terms with clear code examples. I have laid it out so the post can be easily used as a quick reference guide.

If you are going to use strings a lot then I recommend you read the first section as it applies to a lot of the functions. Otherwise you can read in order or just go to the section you require.

Read This First!

The following two points are very important when dealing with VBA string functions.

The Original String is not Changed

An important point to remember is that the VBA string functions do not change the original string. They return a new string with the changes the function made. If you want to change the original string you simply assign the result to the original string. See the section Extracting Part of a String for examples of this.

How To Use Compare

Some of the string functions such as StrComp() and Instr() etc. have an optional Compare parameter. This works as follows:

vbTextCompare: Upper and lower case are considered the same

vbBinaryCompare: Upper and lower case are considered different

The following code uses the string comparison function StrComp() to demonstrate the Compare parameter

' https://excelmacromastery.com/
Sub Comp1()

    ' Prints 0  : Strings match
    Debug.Print StrComp("ABC", "abc", vbTextCompare)
    ' Prints -1 : Strings do not match
    Debug.Print StrComp("ABC", "abc", vbBinaryCompare)

End Sub

You can use the Option Compare setting instead of having to use this parameter each time. Option Compare is set at the top of a Module. Any function that uses the Compare parameter will take this setting as the default. The two ways to use Option Compare are:

1. Option Compare Text: makes vbTextCompare the default Compare argument

' https://excelmacromastery.com/
Option Compare Text

Sub Comp2()
    ' Strings match - uses vbCompareText as Compare argument
    Debug.Print StrComp("ABC", "abc")
    Debug.Print StrComp("DEF", "def")
End Sub

2. Option Compare Binary: Makes vbBinaryCompare the default Compare argument

' https://excelmacromastery.com/
Option Compare Binary

Sub Comp2()
    ' Strings do not match - uses vbCompareBinary as Compare argument
    Debug.Print StrComp("ABC", "abc")
    Debug.Print StrComp("DEF", "def")
End Sub

If Option Compare is not used then the default is Option Compare Binary.

Now that you understand these two important points about string we can go ahead and look at the string functions individually.

Go back to menu

Appending Strings

VBA String Functions - Smaller

ABC Cube Pile © Aleksandr Atkishkin | Dreamstime.com

You can append strings using the & operator. The following code shows some examples of using it

' https://excelmacromastery.com/
Sub Append()

    Debug.Print "ABC" & "DEF"
    Debug.Print "Jane" & " " & "Smith"
    Debug.Print "Long " & 22
    Debug.Print "Double " & 14.99
    Debug.Print "Date " & #12/12/2015#

End Sub

You can see in the example that different types such as dates and number are automatically converted to strings. You may see the + operator being used to append strings. The difference is that this operator will only work with string types. If you try to use it with other type you will get an error.

    ' This will give the error message:  "Type Mismatch"
    Debug.Print "Long " + 22

If you want to do more complex appending of strings then you may wish to use the Format function described below.

Go back to menu

Extracting Part of a String

The functions discussed in this section are useful when dealing with basic extracting from a string. For anything more complicated you might want to check out my post on How to Easily Extract From Any String Without Using VBA InStr.

Function Parameters Description Example
Left string, length Return chars from left side Left(«John Smith»,4)
Right string, length Return chars from right side Right(«John Smith»,5)
Mid string, start, length Return chars from middle Mid(«John Smith»,3,2)

The Left, Right, and Mid functions are used to extract parts of a string. They are very simple functions to use. Left reads characters from the left, Right from the right and Mid from a starting point that you specify.

' https://excelmacromastery.com/
Sub UseLeftRightMid()

    Dim sCustomer As String
    sCustomer = "John Thomas Smith"

    Debug.Print Left(sCustomer, 4)  '  Prints: John
    Debug.Print Right(sCustomer, 5) '  Prints: Smith

    Debug.Print Left(sCustomer, 11)  '  Prints: John Thomas
    Debug.Print Right(sCustomer, 12)  '  Prints: Thomas Smith

    Debug.Print Mid(sCustomer, 1, 4) ' Prints: John
    Debug.Print Mid(sCustomer, 6, 6) ' Prints: Thomas
    Debug.Print Mid(sCustomer, 13, 5) ' Prints: Smith

End Sub

As mentioned in the previous section, VBA string functions do not change the original string. Instead, they return the result as a new string.

In the next example you can see that the string Fullname was not changed after using the Left function

' https://excelmacromastery.com/
Sub UsingLeftExample()

    Dim Fullname As String
    Fullname = "John Smith"

    Debug.Print "Firstname is: "; Left(Fullname, 4)
    ' Original string has not changed
    Debug.Print "Fullname is: "; Fullname

 End Sub

If you want to change the original string you simply assign it to the return value of the function

' https://excelmacromastery.com/
Sub ChangingString()

    Dim name As String
    name = "John Smith"

    ' Assign return string to the name variable
    name = Left(name, 4)

    Debug.Print "Name is: "; name

 End Sub

Go back to menu

Searching Within a String

Function Params Description Example
InStr String1, String2 Finds position of string InStr(«John Smith»,»h»)
InStrRev StringCheck, StringMatch Finds position of string from end InStrRev(«John Smith»,»h»)

InStr and InStrRev are VBA functions used to search through strings for a substring. If the search string is found then the position(from the start of the check string) of the search string is returned. If the search string is not found then zero is returned. If either string is null then null is returned.

InStr Description of Parameters

InStr() Start[Optional], String1, String2, Compare[Optional]

  • Start As Long[Optional – Default is 1]: This is a number that specifies the starting search position from the left
  • String1 As String: The string to search
  • String2 As String: The string to search for
  • Compare As vbCompareMethod : See the section on Compare above for more details

InStr Use and Examples

InStr returns the first position in a string where a given substring is found. The following shows some examples of using it

' https://excelmacromastery.com/
Sub FindSubString()

    Dim name As String
    name = "John Smith"

    ' Returns 3 - position of first h
    Debug.Print InStr(name, "h")
    ' Returns 10 - position of first h starting from position 4
    Debug.Print InStr(4, name, "h")
    ' Returns 8
    Debug.Print InStr(name, "it")
    ' Returns 6
    Debug.Print InStr(name, "Smith")
    ' Returns 0 - string "SSS" not found
    Debug.Print InStr(name, "SSS")

End Sub

InStrRev Description of Parameters

InStrRev() StringCheck, StringMatch, Start[Optional], Compare[Optional]

  • StringCheck As String: The string to search
  • StringMatch: The string to search for
  • Start As Long[Optional – Default is -1]: This is a number that specifies the starting search position from the right
  • Compare As vbCompareMethod: See the section on Compare above for more details

InStrRev Use and Examples

The InStrRev function is the same as InStr except that it searches from the end of the string. It’s important to note that the position returned is the position from the start. Therefore if there is only one instance of the search item then both InStr() and InStrRev() will return the same value.

The following code show some examples of using InStrRev

' https://excelmacromastery.com/
Sub UsingInstrRev()

    Dim name As String
    name = "John Smith"

    ' Both Return 1 - position of the only J
    Debug.Print InStr(name, "J")
    Debug.Print InStrRev(name, "J")

    ' Returns 10 - second h
    Debug.Print InStrRev(name, "h")
    ' Returns 3 - first h as searches from position 9
    Debug.Print InStrRev(name, "h", 9)

    ' Returns 1
    Debug.Print InStrRev(name, "John")

End Sub

The InStr and InStrRev functions are useful when dealing with basic string searches. However, if you are going to use them for extracting text from a string they can make things complicated. I have written about a much better way to do this in my post How to Easily Extract From Any String Without Using VBA InStr.

Go back to menu

Removing Blanks

Function Params Description Example
LTrim string Removes spaces from left LTrim(» John «)
RTrim string Removes spaces from right RTrim(» John «)
Trim string Removes Spaces from left and right Trim(» John «)

The Trim functions are simple functions that remove spaces from either the start or end of a string.

Trim Functions Use and Examples

  • LTrim removes spaces from the left of a string
  • RTrim removes spaces from the right of a string
  • Trim removes spaces from the left and right of a string
' https://excelmacromastery.com/
Sub TrimStr()

    Dim name As String
    name = "  John Smith  "

    ' Prints "John Smith  "
    Debug.Print LTrim(name)
    ' Prints "  John Smith"
    Debug.Print RTrim(name)
    ' Prints "John Smith"
    Debug.Print Trim(name)

End Sub

Go back to menu

Length of a String

Function Params Description Example
Len string Returns length of string Len («John Smith»)

Len is a simple function when used with a string. It simply returns the number of characters the string contains. If used with a numeric type such as long it will return the number of bytes.

' https://excelmacromastery.com/
Sub GetLen()

    Dim name As String
    name = "John Smith"

    ' Prints 10
    Debug.Print Len("John Smith")
    ' Prints 3
    Debug.Print Len("ABC")

    ' Prints 4 as Long is 4 bytes in size
    Dim total As Long
    Debug.Print Len(total)

End Sub

Go back to menu

Reversing a String

Function Params Description Example
StrReverse string Reverses a string StrReverse («John Smith»)

StrReverse is another easy-to-use function. It simply returns the given string with the characters reversed.

' https://excelmacromastery.com/
Sub RevStr()

    Dim s As String
    s = "Jane Smith"
    ' Prints: htimS enaJ
    Debug.Print StrReverse(s)

End Sub

Go back to menu

Comparing Strings

Function Params Description Example
StrComp string1, string2 Compares 2 strings StrComp («John», «John»)

The function StrComp is used to compare two strings. The following subsections describe how it is used.

Description of Parameters

StrComp()  String1, String2, Compare[Optional]

  • String1 As String: The first string to compare
  • String2 As String: The second string to compare
  • Compare As vbCompareMethod : See the section on Compare above for more details

StrComp Return Values

Return Value Description
0 Strings match
-1 string1 less than string2
1 string1 greater than string2
Null if either string is null

Use and Examples

The following are some examples of using the StrComp function

' https://excelmacromastery.com/
Sub UsingStrComp()

   ' Returns 0
   Debug.Print StrComp("ABC", "ABC", vbTextCompare)
   ' Returns 1
   Debug.Print StrComp("ABCD", "ABC", vbTextCompare)
   ' Returns -1
   Debug.Print StrComp("ABC", "ABCD", vbTextCompare)
   ' Returns Null
   Debug.Print StrComp(Null, "ABCD", vbTextCompare)

End Sub

Compare Strings using Operators

You can also use the equals sign to compare strings. The difference between the equals comparison and the StrComp function are:

  1. The equals sign returns only true or false.
  2. You cannot specify a Compare parameter using the equal sign – it uses the “Option Compare” setting.

The following shows some examples of using equals to compare strings

' https://excelmacromastery.com/
Option Compare Text

Sub CompareUsingEquals()

    ' Returns true
    Debug.Print "ABC" = "ABC"
    ' Returns true because "Compare Text" is set above
    Debug.Print "ABC" = "abc"
    ' Returns false
    Debug.Print "ABCD" = "ABC"
    ' Returns false
    Debug.Print "ABC" = "ABCD"
    ' Returns null
    Debug.Print Null = "ABCD"

End Sub

The Operator “<>” means “does not equal”. It is essentially the opposite of using the equals sign as the following code shows

' https://excelmacromastery.com/
Option Compare Text

Sub CompareWithNotEqual()

    ' Returns false
    Debug.Print "ABC" <> "ABC"
    ' Returns false because "Compare Text" is set above
    Debug.Print "ABC" <> "abc"
    ' Returns true
    Debug.Print "ABCD" <> "ABC"
    ' Returns true
    Debug.Print "ABC" <> "ABCD"
    ' Returns null
    Debug.Print Null <> "ABCD"

End Sub

Go back to menu

Comparing Strings using Pattern Matching

Operator Params Description Example
Like string, string pattern checks if string has the given pattern «abX» Like «??X»
«54abc5» Like «*abc#»
Token Meaning
? Any single char
# Any single digit(0-9)
* zero or more characters
[charlist] Any char in the list
[!charlist] Any char not in the char list

Pattern matching is used to determine if a string has a particular pattern of characters. For example, you may want to check that a customer number has 3 digits followed by 3 alphabetic characters or a string has the letters XX followed by any number of characters.

If the string matches the pattern then the return value is true, otherwise it is false.

Pattern matching is similar to the VBA Format function in that there are almost infinite ways to use it. In this section I am going to give some examples that will explain how it works. This should cover the most common uses. If you need more information about pattern matching you can refer to the MSDN Page for the Like operator.

Lets have a look at a basic example using the tokens. Take the following pattern string

[abc][!def]?#X*

Let’s look at how this string works
[abc] a character that is either a,b or c
[!def] a character that is not d,e or f
? any character
# any digit
X the character X
* followed by zero or more characters

Therefore the following string is valid
apY6X

a is one of abc
p is not one of the characters d, e or f
Y is any character
6 is a digit
X is the letter X

The following code examples show the results of various strings with this pattern

' https://excelmacromastery.com/
Sub Patterns()

    ' True
    Debug.Print 1; "apY6X" Like "[abc][!def]?#X*"
    ' True - any combination of chars after x is valid
    Debug.Print 2; "apY6Xsf34FAD" Like "[abc][!def]?#X*"
    ' False - char d not in [abc]
    Debug.Print 3; "dpY6X" Like "[abc][!def]?#X*"
    ' False - 2nd char e is in [def]
    Debug.Print 4; "aeY6X" Like "[abc][!def]?#X*"
    ' False - A at position 4 is not a digit
    Debug.Print 5; "apYAX" Like "[abc][!def]?#X*"
    ' False - char at position 5 must be X
    Debug.Print 6; "apY6Z" Like "[abc][!def]?#X*"

End Sub

Real-World Example of Pattern Matching

To see a real-world example of using pattern matching check out Example 3: Check if a filename is valid.

Important Note on VBA Pattern Matching

The Like operator uses either Binary or Text comparison based on the Option Compare setting. Please see the section on Compare above for more details.

Go back to menu

Replace Part of a String

Function Params Description Example
Replace string, find, replace,
start, count, compare
Replaces a substring with a substring Replace («Jon»,»n»,»hn»)

Replace is used to replace a substring in a string by another substring. It replaces all instances of the substring that are found by default.

Replace Description of Parameters

Replace()  Expression, Find, Replace, Start[Optional], Count[Optional], Compare[Optional]

  • Expression As String: The string to replace chars in
  • Find As String: The substring to replace in the Expression string
  • Replace As String: The string to replace the Find substring with
  • Start As Long[Optional – Default is 1]: The start position in the string
  • Count As Long[Optional – Default is -1]: The number of substitutions to make. The default -1 means all.
  • Compare As vbCompareMethod : See the section on Compare above for more details

Use and Examples

The following code shows some examples of using the Replace function

' https://excelmacromastery.com/
Sub ReplaceExamples()

    ' Replaces all the question marks with(?) with semi colons(;)
    Debug.Print Replace("A?B?C?D?E", "?", ";")
    ' Replace Smith with Jones
    Debug.Print Replace("Peter Smith,Ann Smith", "Smith", "Jones")
    ' Replace AX with AB
    Debug.Print Replace("ACD AXC BAX", "AX", "AB")

End Sub

Output
A;B;C;D;E
Peter Jones,Sophia Jones
ACD ABC BAB

In the following examples we use the Count optional parameter. Count determines the number of substitutions to make. So for example, setting Count equal to one means that only the first occurrence will be replaced.

' https://excelmacromastery.com/
Sub ReplaceCount()

    ' Replaces first question mark only
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=1)
    ' Replaces first three question marks
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=3)

End Sub

Output
A;B?C?D?E
A;B;C;D?E

The Start optional parameter allow you to return part of a string. The position you specify using Start is where it starts returning the string from. It will not return any part of the string before this position whether a replace was made or not.

' https://excelmacromastery.com/
Sub ReplacePartial()

    ' Use original string from position 4
    Debug.Print Replace("A?B?C?D?E", "?", ";", Start:=4)
    ' Use original string from position 8
    Debug.Print Replace("AA?B?C?D?E", "?", ";", Start:=8)
    ' No item replaced but still only returns last 2 characters
    Debug.Print Replace("ABCD", "X", "Y", Start:=3)

End Sub

Output
;C;D;E
;E
CD

Sometimes you may only want to replace only upper or lower case letters. You can use the Compare parameter to do this. This is used in a lot of string functions.  For more information on this check out the Compare section above.

' https://excelmacromastery.com/
Sub ReplaceCase()

    ' Replace capital A's only
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbBinaryCompare)
    ' Replace All A's
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbTextCompare)

End Sub

Output
XaXa
XXXX

Multiple Replaces

If you want to replace multiple values in a string you can nest the calls. In the following code we want to replace X and Y with A and B respectively.

' https://excelmacromastery.com/
Sub ReplaceMulti()

    Dim newString As String

    ' Replace A with X
    newString = Replace("ABCD ABDN", "A", "X")
    ' Now replace B with Y in new string
    newString = Replace(newString, "B", "Y")

    Debug.Print newString

End Sub

In the next example we will change the above code to perform the same task. We will use the return value of the first replace as the argument for the second replace.

' https://excelmacromastery.com/
Sub ReplaceMultiNested()

    Dim newString As String

    ' Replace A with X and B with Y
    newString = Replace(Replace("ABCD ABDN", "A", "X"), "B", "Y")

    Debug.Print newString

End Sub

The result of both of these Subs is
XYCD XYDN

Go back to menu

Convert Types to String(Basic)

This section is about converting numbers to a string. A very important point here is that most the time VBA will automatically convert to a string for you. Let’s look at some examples

' https://excelmacromastery.com/
Sub AutoConverts()

    Dim s As String
    ' Automatically converts number to string
    s = 12.99
    Debug.Print s

    ' Automatically converts multiple numbers to string
    s = "ABC" & 6 & 12.99
    Debug.Print s

    ' Automatically converts double variable to string
    Dim d As Double, l As Long
    d = 19.99
    l = 55
    s = "Values are " & d & " " & l
    Debug.Print s

End Sub

When you run the above code you can see that the number were automatically converted to strings. So when you assign a value to a string VBA will look after the conversion for you most of the time. There are conversion functions in VBA and in the following sub sections we will look at the reasons for using them.

Explicit Conversion

Function Params Description Example
CStr expression Converts a number variable to a string CStr («45.78»)
Str number Converts a number variable to a string Str («45.78»)

In certain cases you may want to convert an item to a string without have to place it in a string variable first. In this case you can use the Str or CStr functions. Both take an  expression as a function and this can be any type such as long, double, data or boolean.

Let’s look at a simple example. Imagine you are reading a list of values from different types of cells to a collection. You can use the Str/CStr functions to ensure they are all stored as strings. The following code shows an example of this

' https://excelmacromastery.com/
Sub UseStr()

    Dim coll As New Collection
    Dim c As Range

    ' Read cell values to collection
    For Each c In Range("A1:A10")
        ' Use Str to convert cell value to a string
        coll.Add Str(c)
    Next

    ' Print out the collection values and type
    Dim i As Variant
    For Each i In coll
        Debug.Print i, TypeName(i)
    Next

End Sub

In the above example we use Str to convert the value of the cell to a string. The alternative to this would be to assign the value to a string and then assigning the string to the collection. So you can see that using Str here is much more efficient.

Multi Region

The difference between the Str and CStr functions is that CStr converts based on the region. If your macros will be used in multiple regions then you will need to use CStr for your string conversions.

It is good to practise to use CStr when reading values from cells. If your code ends up being used in another region then you will not have to make any changes to make it work correctly.

Go back to menu

Convert String to Number- CLng, CDbl, Val etc.

Function Returns Example
CBool Boolean CBool(«True»), CBool(«0»)
CCur Currency CCur(«245.567»)
CDate Date CDate(«1/1/2017»)
CDbl Double CCur(«245.567»)
CDec Decimal CDec(«245.567»)
CInt Integer CInt(«45»)
CLng Long Integer CLng(«45.78»)
CVar Variant CVar(«»)

The above functions are used to convert strings to various types. If you are assigning to a variable of this type then VBA will do the conversion automatically.

' https://excelmacromastery.com/
Sub StrToNumeric()

    Dim l As Long, d As Double, c As Currency
    Dim s As String
    s = "45.923239"

    l = s
    d = s
    c = s

    Debug.Print "Long is "; l
    Debug.Print "Double is "; d
    Debug.Print "Currency is "; c

End Sub

Using the conversion types gives more flexibility. It means you can determine the type at runtime. In the following code we set the type based on the sType argument passed to the PrintValue function. As this type can be read from an external source such as a cell, we can set the type at runtime. If we declare a variable as Long then it will always be long when the code runs.

' https://excelmacromastery.com/
Sub Test()
    ' Prints  46
    PrintValue "45.56", "Long"
    ' Print 45.56
    PrintValue "45.56", ""
End Sub

Sub PrintValue(ByVal s As String, ByVal sType As String)

    Dim value

    ' Set the data type based on a type string
    If sType = "Long" Then
        value = CLng(s)
    Else
        value = CDbl(s)
    End If
    Debug.Print "Type is "; TypeName(value); value

End Sub

If a string is not a valid number(i.e. contains symbols other numeric) then you get a “Type Mismatch” error.

' https://excelmacromastery.com/
Sub InvalidNumber()

    Dim l As Long

    ' Will give type mismatch error
    l = CLng("45A")

End Sub

The Val Function

The value function convert numeric parts of a string to the correct number type.

The Val function converts the first numbers it meets. Once it meets letters in a string it stops. If there are only letters then it returns zero as the value. The following code shows some examples of using Val

' https://excelmacromastery.com/
Sub UseVal()

    ' Prints 45
    Debug.Print Val("45 New Street")

    ' Prints 45
    Debug.Print Val("    45 New Street")

    ' Prints 0
    Debug.Print Val("New Street 45")

    ' Prints 12
    Debug.Print Val("12 f 34")

End Sub

The Val function has two disadvantages

1. Not Multi-Region – Val does not recognise international versions of numbers such as using commas instead of decimals. Therefore you should use the above conversion functions when you application will be used in multiple regions.

2. Converts invalid strings to zero – This may be okay in some instances but in most cases it is better if an invalid string raises an error. The application is then aware there is a problem and can act accordingly. The conversion functions such as CLng will raise an error if the string contains non-numeric characters.

Go back to menu

Generate a String of items – String Function

Function Params Description Example
String number, character Converts a number variable to a string String (5,»*»)

The String function is used to generate a string of repeated characters. The first argument is the number of times to repeat it, the second argument is the character.

' https://excelmacromastery.com/
Sub GenString()

    ' Prints: AAAAA
    Debug.Print String(5, "A")
    ' Prints: >>>>>
    Debug.Print String(5, 62)
    ' Prints: (((ABC)))
    Debug.Print String(3, "(") & "ABC" & String(3, ")")

End Sub

Go back to menu

Convert Case/Unicode – StrConv, UCase, LCase

Function Params Description Example
StrConv string, conversion, LCID Converts a String StrConv(«abc»,vbUpperCase)

If you want to convert the case of a string to upper or lower you can use the UCase and LCase functions for upper and lower respectively. You can also use the StrConv function with the vbUpperCase or vbLowerCase argument. The following code shows example of using these three functions

' https://excelmacromastery.com/
Sub ConvCase()

    Dim s As String
    s = "Mary had a little lamb"

    ' Upper
    Debug.Print UCase(s)
    Debug.Print StrConv(s, vbUpperCase)

    ' Lower
    Debug.Print LCase(s)
    Debug.Print StrConv(s, vbLowerCase)

    ' Sets the first letter of each word to upper case
    Debug.Print StrConv(s, vbProperCase)

End Sub

Output
MARY HAD A LITTLE LAMB
MARY HAD A LITTLE LAMB
mary had a little lamb
mary had a little lamb
Mary Had A Little Lamb

Other Conversions

As well as case the StrConv can perform other conversions based on the Conversion parameter. The following table shows a list of the different parameter values and what they do. For more information on StrConv check out the MSDN Page.

Constant Value Converts
vbUpperCase 1 to upper case
vbLowerCase 2 to lower case
vbProperCase 3 first letter of each word to uppercase
vbWide* 4 from Narrow to Wide
vbNarrow* 8 from Wide to Narrow
vbKatakana** 16 from Hiragana to Katakana
vbHiragana 32 from Katakana to Hiragana
vbUnicode 64 to unicode
vbFromUnicode 128 from unicode

Go back to menu

Using Strings With Arrays

Function Params Description Example
Split expression, delimiter,
limit, compare
Parses a delimited string to an array arr = Split(«A;B;C»,»;»)
Join source array, delimiter Converts a one dimensional array to a string s = Join(Arr, «;»)

String to Array using Split

You can easily parse a delimited string into an array. You simply use the Split function with the delimiter as parameter. The following code shows an example of using the Split function.

' https://excelmacromastery.com/
Sub StrToArr()

    Dim arr() As String
    ' Parse string to array
    arr = Split("John,Jane,Paul,Sophie", ",")

    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

Output
John
Jane
Paul
Sophie

You can find a complete guide to the split function here.

Array to String using Join

If you want to build a string from an array you can do so easily using the Join function. This is essentially a reverse of the Split function. The following code provides an example of using Join

' https://excelmacromastery.com/
Sub ArrToStr()

    Dim Arr(0 To 3) As String
    Arr(0) = "John"
    Arr(1) = "Jane"
    Arr(2) = "Paul"
    Arr(3) = "Sophie"

    ' Build string from array
    Dim sNames As String
    sNames = Join(Arr, ",")

    Debug.Print sNames

End Sub

Output
John,Jane,Paul,Sophie

Go back to menu

Formatting a String

Function Params Description Example
Format expression, format,
firstdayofweek, firstweekofyear
Formats a string Format(0.5, «0.00%»)

The Format function is used to format a string based on given instructions. It is mostly used to place a date or number in certain format. The examples below show the most common ways you would format a date.

' https://excelmacromastery.com/
Sub FormatDate()

    Dim s As String
    s = "31/12/2015 10:15:45"

    ' Prints: 31 12 15
    Debug.Print Format(s, "DD MM YY")
    ' Prints: Thu 31 Dec 2015
    Debug.Print Format(s, "DDD DD MMM YYYY")
    ' Prints: Thursday 31 December 2015
    Debug.Print Format(s, "DDDD DD MMMM YYYY")
    ' Prints: 10:15
    Debug.Print Format(s, "HH:MM")
    ' Prints: 10:15:45 AM
    Debug.Print Format(s, "HH:MM:SS AM/PM")

End Sub

The following examples are some common ways of formatting numbers

' https://excelmacromastery.com/
Sub FormatNumbers()

    ' Prints: 50.00%
    Debug.Print Format(0.5, "0.00%")
    ' Prints: 023.45
    Debug.Print Format(23.45, "00#.00")
    ' Prints: 23,000
    Debug.Print Format(23000, "##,000")
    ' Prints: 023,000
    Debug.Print Format(23000, "0##,000")
    ' Prints: $23.99
    Debug.Print Format(23.99, "$#0.00")

End Sub

The Format function is quite a large topic and could use up a full post on it’s own. If you want more information then the MSDN Format Page provides a lot of information.

Helpful Tip for Using Format

A quick way to figure out the formatting to use is by using the cell formatting on an Excel worksheet. For example add a number to a cell. Then right click and format the cell the way you require. When you are happy with the format select Custom from the category listbox on the left.  When you select this you can see the format string in the type textbox(see image below). This is the string format you can use in VBA.

VBA Format Function

Format Cells Dialog

Go back to menu

Conclusion

In almost any type of programming, you will spend a great deal of time manipulating strings. This post covers the many different ways you use strings in VBA.

To get the most from use the table at the top to find the type of function you wish to use. Clicking on the left column of this function will bring you to that section.

If you are new to strings in VBA, then I suggest you check out the Read this First section before using any of the functions.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Работа с текстом в коде VBA Excel. Функции, оператор & и другие ключевые слова для работы с текстом. Примеры использования некоторых функций и ключевых слов.

Функции для работы с текстом

Основные функции для работы с текстом в VBA Excel:

Функция Описание
Asc(строка) Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/».
Chr(код символа) Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/».
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее…
InStr([начало], строка1, строка2, [сравнение]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее…
InstrRev(строка1, строка2, [начало, [сравнение]]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее…
Join(SourceArray,[Delimiter]) Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее…
LCase(строка) Преобразует буквенные символы строки в нижний регистр.
Left(строка, длина) Возвращает левую часть строки с заданным количеством символов. Подробнее…
Len(строка) Возвращает число символов, содержащихся в строке.
LTrim(строка) Возвращает строку без начальных пробелов (слева). Подробнее…
Mid(строка, начало, [длина]) Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее…
Replace(expression, find, replace, [start], [count], [compare]) Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее…
Right(строка, длина) Возвращает правую часть строки с заданным количеством символов. Подробнее…
RTrim(строка) Возвращает строку без конечных пробелов (справа). Подробнее…
Space(число) Возвращает строку, состоящую из указанного числа пробелов. Подробнее…
Split(Expression,[Delimiter],[Limit],[Compare]) Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее…
StrComp(строка1, строка2, [сравнение]) Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее…
StrConv(string, conversion) Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее…
String(число, символ) Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее…
StrReverse(строка) Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее…
Trim(строка) Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее…
UCase(строка) Преобразует буквенные символы строки в верхний регистр.
Val(строка) Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее…
WorksheetFunction.Trim(строка) Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы.

В таблице перечислены основные функции VBA Excel для работы с текстом. С полным списком всевозможных функций вы можете ознакомиться на сайте разработчика.

Ключевые слова для работы с текстом

Ключевое слово Описание
& Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String.
vbCrLf Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2).
vbNewLine Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2).

Примеры

Вывод прямых парных кавычек

Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:

Sub Primer1()

    ‘Вывод одной прямой парной кавычки

MsgBox Chr(34)

    ‘Отображение текста в прямых кавычках

MsgBox Chr(34) & «Волга» & Chr(34)

    ‘Вывод 10 прямых парных кавычек подряд

MsgBox String(10, Chr(34))

End Sub

Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.

Отображение слов наоборот

Преобразование слова «налим» в «Милан»:

Sub Primer2()

Dim stroka

    stroka = «налим»

    stroka = StrReverse(stroka) ‘милан

    stroka = StrConv(stroka, 3) ‘Милан

MsgBox stroka

End Sub

или одной строкой:

Sub Primer3()

MsgBox StrConv(StrReverse(«налим»), 3)

End Sub

Преобразование слова «лето» в «отель»:

Sub Primer4()

Dim stroka

    stroka = «лето»

    stroka = StrReverse(stroka) ‘отел

    stroka = stroka & «ь» ‘отель

MsgBox stroka

End Sub

или одной строкой:

Sub Primer5()

MsgBox StrReverse(«лето») & «ь»

End Sub

Печатная машинка

Следующий код VBA Excel в замедленном режиме посимвольно печатает указанную строку на пользовательской форме, имитируя печатную машинку.

Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):

Пользовательская форма с элементами управления Label и CommandButton

Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub StopSub(Pause As Single)

Dim Start As Single

Start = Timer

    Do While Timer < Start + Pause

       DoEvents

    Loop

End Sub

Private Sub CommandButton1_Click()

Dim stroka As String, i As Byte

stroka = «Печатная машинка!»

Label1.Caption = «»

    For i = 1 To Len(stroka)

        Call StopSub(0.25) ‘пауза в секундах

        ‘следующая строка кода добавляет очередную букву

        Label1.Caption = Label1.Caption & Mid(stroka, i, 1)

    Next

End Sub

Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


02 Oct Working with Strings in Excel VBA

Posted at 02:54h
in Excel VBA
0 Comments

Howdee! If you’ve ever written any VBA code, you’ve likely had to edit strings in Excel VBA. It can be challenging and more than a little frustrating, especially if you’re not familiar with the tools available to you within the framework. Have you ever had to transform a string of last name comma first name to a traditional full name field in code? Ever had to pull a piece of information out of a string of dozens of characters? Then this article is for you. With that done, let’s dive right in!

VBA InStr & InStrRev Functions

These two functions are, in my opinion, the most crucial text functions to understand when it comes to getting data from inside a string of text in Excel. Once you understand these, you can begin to combine them with other functions to write truly powerful text parsing code.

The Instr function returns the starting position, as a number, of a string within a string of text. For example, we could search the string “I owe you 25 dollars on September 25th” for the literal string “25”. Depending on which function you use you would get different results! Let’s examine the below code:

Sub Instr_InstrRev_Example()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox InStr(1, stringExample, "25") 'returns 11

MsgBox InStrRev(stringExample, "25") 'returns 35

End Sub

The first message box will display “11” and the second will display “35”. This is important to think about when writing your code, if you need the first or last occurrence of a string within a string, then these functions will serve you very well. In the interest of being thorough, here is the syntax for both functions:

InStr( [start], string, substring, [compare] )

Start is an optional parameter that tells the function which character to begin searching. If you omit it, the compiler will start at the first character. String represents the string you’re searching while substring is the string you’re searching for. The compare parameter is also optional and I’ve rarely had need to use it so I won’t confuse you with it now but you’ll almost always use text compare.

InStrRev (StringCheck, StringMatch, [Start], [Compare])

StringCheck is the string you’re searching while StringMatch is the string you’re searching for. The start variable is optional as it was in InStr. The difference is it starts at the end of the string if omitted. Compare is the same as from the previous function also.

You might be asking yourself what use the VBA Instr and InstrRev functions are if they only return the starting position of a first or last occurrence of a substring. Once we introduce the next function, it will begin to make more sense.

VBA Mid Function

The Mid VBA function extracts a substring from a string based on a starting position and length that you specify. Before diving into examples, let’s look at the syntax:

Mid(text, start_position, number_of_characters)

Text is the full string of text from which you want to remove a substring. Start_position is an integer that represents the starting position of the first character of the string you wish to remove. Finally, number_of_characters is an integer representing the number of characters you wish to return.

Continuing with the sentence we used in the prior example, let’s examine the following code:

Sub MidExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Mid(stringExample, 1, 5)

End Sub

In this example, our Mid VBA function would return the string “I owe”. That’s because we have told the function to start at the first character in the string and return 5 characters from that point, including the starting character. Combining this function with the two InStr functions from the prior example, you can dynamically tell your Mid function where to start returning text from within a string. Using these functions together is how I primarily handle working with strings in Excel VBA.

VBA Left & Right Functions

If you’ve been using Excel for any period of time, you’ve probably either seen or used the Left and Right worksheet functions. Both of these functions exist in VBA and the syntax is the exact same. So, if you’re familiar with these functions, you can probably skip ahead to the next section but, in the interest of thoroughness, I want to cover these functions for folks who may not have used them before.

By their names, you can probably infer what these two functions do. The Left function returns a specific number of characters from the beginning of a string, while the Right function returns a specified number of characters form the end of a string. The syntax for them looks like this:

Left(text, number_of_characters)

Right(text, number_of_characters)

In both functions, the text input is the string you’re wanting to return a portion of, while the number_of_characters input is an integer representing the number of characters you wish to return. Let’s use our $25 sentence to examine the results in the following code:

Sub LeftRightExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Left(stringExample, 5)
MsgBox Right(stringExample, 5)

End Sub

In this example, the left function would return “I owe” while the Right example would return “ 25th”. The VBA functions Left & Right are very useful when you need to return the beginning X number of characters or the ending X number of characters from a string. It can also be used to return the beginning/ending portions of substrings when other functions are nested inside the text input. While I use these less than the previous two, they’re incredibly useful when just grabbing the beginning or ends of strings in Excel VBA.

VBA Replace Function

The last function I want to cover in depth is the VBA Replace function. As you might expect from its name, the Replace function replaces a sequence of characters with another sequence of characters. This can be useful when you’re preparing data and need to remove invalid characters from a string, performing what if analysis and need to alter a string based on inputs, etc. Let’s take our sentence we’ve been using and assume we need to change the 25th due date to the 30th. First, let’s examine the syntax to figure out how to do that.

Replace(string1, find, replacement, [start], [count], [compare])

String1 represents the string you want search. For us, this is our entire sentence. Find represents the string we are searching string1 for to perform the replace. The last required field, replacement, is the sequence of characters you want to replace string1 with. Start, an optional parameter, tells the search where to start. If you omit this, it starts at the beginning of the string. Count determines the number of replacements to make. If you leave this blank, it will perform the replace for every occurrence of find. Lastly, compare determines how to compare the strings. As before, you’ll almost always leave this to it’s default of text compare. The code for our example looks like this:

Sub ReplaceExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Replace(stringExample, "25th", "30th")

End Sub

Other Useful Functions to Edit Strings in Excel VBA

Len(text)

The Len VBA function accepts a string input and returns the number of characters in that string.

UCase(text) & LCase(text)

Both of these functions accept a string input and the UCase function will return the string converted to all upper-case characters while the LCase function returns the string with all characters converted to lower-case. This is very useful when doing string comparisons in VBA.

Str(number)

Str is a useful function that will accept a number from your code and return it as a string so you can then use string and text VBA functions on the number.

Split(expression, [delimiter], [limit], [compare])

Split is a very useful function that will split out substrings based on a delimiter. Expression is the text input. The optional parameter delimiter will default to a space delimiter but you can assign a comma, semi-colon, etc. Limit is also optional and determine the number of strings to split out. This will default to all strings if left blank. Compare, as with other formulas can be almost always be omitted from your function.

Real World Examples

The above functions, while good for explanation purposes, don’t always tell the full story since they aren’t real world examples of how to use these functions. I thought I would toss out a couple of examples of how to use VBA text functions to manipulate strings in Excel VBA with a couple of problems I’ve run into over the years.

The most common issue I run into with data sets, is that there is no universally accepted way to export full names. Almost every database stores names as first and last name fields. The issue is that many systems concatenate these fields together on export but may do it differently. For example, your time tracking system might export names in the format “FirstName LastName” while your payroll system exports names in the format “LastName, FirstName”. If you’re trying to match these names up on a weekly basis for payroll, this can get annoying quickly. Writing a macro to transform one or the other can save you a lot of time over the course of the year.

Sub LastNameFirstNameExample()
Dim lastrow As Long, i As Long
Dim sht As Worksheet
Dim str As String

Set sht = Worksheets("Name Transform Example")
lastrow = sht.UsedRange.Rows.Count

For i = 2 To lastrow
    str = Cells(i, 1)
    Cells(i, 2) = Mid(str, InStr(1, str, ",") + 2, Len(str) - InStr(1, str, ",") + 2) & " " & _
        Left(str, InStr(1, str, ",") - 1)
Next i

End Sub

working with strings in excel vba

This subroutine is an example of how to turn the “LastName, FirstName” format into the “FirstName LastName” format, as seen in the gif above. First, we define the range we want to perform the conversion on and loop through those cells. While looping, we use a combination of the Mid, InStr, Len, and Left functions to reorder the names. Since all names are separate by a comma, it becomes very easy to find the splitting point between the last name and first name and, by using the Len & InStr functions, we can determine exactly how many characters we need to return. Alternatively, we could have used the Split function like this:

Sub LastNameFirstNameExampleTwo()
Dim lastrow As Long, i As Long
Dim sht As Worksheet
Dim str As String
Dim nameArray() As String

Set sht = Worksheets("Name Transform Example")
lastrow = sht.UsedRange.Rows.Count

For i = 2 To lastrow
    str = Cells(i, 1)
    nameArray = Split(str, ",")
    Cells(i, 2) = LTrim(nameArray(1) & " " & nameArray(0))
Next i

End Sub

The nuts and bolts of this are the same, but this example uses a string array and the Split function inside the loop. You can easily split a string of delimited text into a string array and then reorder it. It’s important to remember that it will return all of the string around the split so we need to use the LTrim function in this case to remove the leading space at the beginning of our end result. Both examples are fine but I prefer the split and array example as it is a bit easier to read.

I hope you enjoyed this brief introduction to working with strings in Excel VBA. As always, the example code is available for download for all subscribers. It’s quick and easy to sign up and I won’t ever spam you with unwanted ads and emails. Let me know in the comments if you have any questions on the above.

Cheers,

R

Join Strings | Left | Right | Mid | Len | Instr

In this chapter, you’ll find the most important functions to manipulate strings in Excel VBA.

Place a command button on your worksheet and add the code lines below. To execute the code lines, click the command button on the sheet.

Join Strings

We use the & operator to concatenate (join) strings.

Code:

Dim text1 As String, text2 As String
text1 = «Hi»
text2 = «Tim»

MsgBox text1 & » » & text2

Result:

Join Strings

Note: to insert a space, use » «

Left

To extract the leftmost characters from a string, use Left.

Code:

Dim text As String
text = «example text»

MsgBox Left(text, 4)

Result:

Left

Right

To extract the rightmost characters from a string, use Right. We can also directly insert text in a function.

Code:

MsgBox Right(«example text», 2)

Result:

Right

Mid

To extract a substring, starting in the middle of a string, use Mid.

Code:

MsgBox Mid(«example text», 9, 2)

Result:

Mid

Note: started at position 9 (t) with length 2. You can omit the third argument if you want to extract a substring starting in the middle of a string, until the end of the string.

Len

To get the length of a string, use Len.

Code:

MsgBox Len(«example text»)

Result:

Len

Note: space (position 8) included!

Instr

To find the position of a substring in a string, use Instr.

Code:

MsgBox Instr(«example text», «am»)

Result:

Instr

Note: string «am» found at position 3. Visit our page about the Instr function for more information and examples.

VBA String functions do not replace the string, but the result of these functions creates a new string. There are many string functions in VBA. They are all categorized under String or Text functions. Some important functions are the LEFT function to get the value from the left and the RIGHT function to get the value from the right or the MID function, LEN, and INSTR function.

String functions are so important. We can extract any characters from the string by finding the number of characters of the supplied string.

We can extract characters from the left side of the string, we can extract from the right side of the string, we can extract from the middle of the string, we can combine two texts, and we can split them at the same time as well.

It is important to have a fair bit of knowledge about all these VBA functionsVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more as part of the large project.

Table of contents
  • Excel VBA String Functions
    • List of Top 6 String Functions in VBA
      • #1 – LEN Function
      • #2 – LEFT Function
      • #3 – RIGHT Function
      • #4 – MID Function
      • #5 – TRIM Function
      • #6 – Instr Function
    • Recommended Articles

List of Top 6 String Functions in VBA

  1. LEN Function
  2. LEFT Function
  3. RIGHT Function
  4. MID Function
  5. TRIM Function
  6. Instr Function

VBA String Functions

One thing we would like to say is that “the VBA string functions are text functions in the worksheet.”

You must have already used LEN, LEFT, RIGHT, MID, and SUBSTITUTE excel functionsSubstitute function in excel is a very useful function which is used to replace or substitute a given text with another text in a given cell, this function is widely used when we send massive emails or messages in a bulk, instead of creating separate text for every user we use substitute function to replace the information.read more to play around with the data. In VBA, too, we can use them to play around with the data.

We will discuss some of the important functions of this article.

You can download this VBA String Functions Excel Template here – VBA String Functions Excel Template

#1 – LEN Function

LEN stands for “LENGTH.” Therefore, it will give us the number of characters involved in the supplied string. For example, if you supply the word “Hello,” LEN in the excelThe Len function returns the length of a given string. It calculates the number of characters in a given string as input. It is a text function in Excel as well as an inbuilt function that can be accessed by typing =LEN( and entering a string as input.read more function will return 5 because there are five characters in the word “Hello.”

The below code will show the example.

Code:

Sub LEN_Example()

  Dim TotalCount As String

  TotalCount = Len("Hello")

  MsgBox TotalCount

End Sub

It will show the result in the message box as 5.

VBA LEN Example

#2 – LEFT Function

We need to use the VBA LEFTExcel VBA Left is an inbuilt worksheet text function that facilitates the user to extract a certain number of characters (denoted as N) from the left side of a string. It helps in pulling the leftmost substring from a particular string in the data set.read more function to extract the characters from the left side of the string. First, take a look at the syntax of the LEFT function.

LEFT Formula

  • The string is what the string we are trying to extract is.
  • Length is nothing but how many characters you need from the left side of the supplied String.

Code:

Sub LEFT_Example()

  Dim FirstName As String

  FirstName = Left("Sachin Tendulkar", 6)

  MsgBox FirstName

End Sub

It will extract the first six characters from the string “Sachin Tendulkar.” So, the result will be the first name,  “Sachin.”

VBA LEFT Example

#3 – RIGHT Function

Like how we have extracted values from the left side of the string similarly, we can also extract from the right side of the string.

The syntax of the RIGHT functionRight function is a text function which gives the number of characters from the end from the string which is from right to left. For example, if we use this function as =RIGHT ( “ANAND”,2) this will give us ND as the result.read more is the same as the LEFT function.

Right Formula

  • The string is what the string we are trying to extract is.
  • Length is nothing but how many characters you need from the right side of the supplied String.

Code:

Sub RIGHT_Example()

  Dim LastName As String

  LastName = Right("Sachin Tendulkar", 9)

  MsgBox LastName

End Sub

It will extract 9 characters from the string “Sachin Tendulkar.” So, the result will be the last name “Tendulkar.”

VBA Right Example

#4 – MID Function

We can extract the characters from the left and right sides and the middle of the string. Below is the syntax of the VBA MID functionVBA MID function extracts the middle values from the supplied sentence or word. It is categorized under the String and Text function and is a worksheet function.read more.

MID formula

  • String to Search: From which string do we need the middle value?
  • Starting Position: What is the starting character position number to extract?
  • Number of Characters to Extract: How many characters need to be extracted from the Starting Position?

For example, if the name is “Sachin Ramesh Tendulkar,” the middle name is “Ramesh” in this string starting position of the character to be extracted 8. Therefore, we need six characters from the starting position. The below code will extract the middle value.

Code:

Sub MID_Example()

  Dim MiddleName As String

  MiddleName = Mid("Sachin Ramesh Tendulkar", 8, 6)

  MsgBox MiddleName

End Sub

It will extract “Ramesh” from the middle of the string “Sachin Ramesh Tendulkar.”

VBA String Functions Example

#5 – TRIM Function

TRIM is the function of cleaning the data. It will eliminate unwanted space characters from the string. First, take a look at the syntax of the TRIM function.

Trim formula

It is straightforward what value or string you want to trim.

For example, assume you have the string “Hello, How are you?.” Here, we have unnecessary space characters before the word “Hello,” so by using TRIM. We can eliminate this.

Code:

Sub TRIM_Example()

  Dim MyValue As String

  MyValue = Trim(" Hello How are you?")

  MsgBox MyValue

End Sub

It will delete the unwanted space characters from the supplied string.

VBA String Functions Example

We have LTRIM and RTRIM functions as well in VBA. For example, LTRIM will delete unwanted spaces from the left side of the string, and RTRIM deletes unwanted spaces from the right side.

#6 – Instr Function

The Instr function helps find the position of the supplied character in the string. The syntax of the INSTR function is as follows:

Instr Formula

  • [Start] From which position of the supplied string do we need the position?
  • [String1] What is the string you are referring to?
  • [String2] What character are you searching for in [String1]?

For example, if you have the word “Recipe” and you want to find the position of the character “e” from the first place below, the code will show the position of the letter “e.”

Code:

Sub INSTR_Example()

  Dim MyValue As String

  MyValue = InStr(1, "Recipe", "e")

  MsgBox MyValue

End Sub

So, from the first position of the string letter “e” position is 2.

VBA String Functions Example

If you want the position of the second appearance of the letter “e,” then you need to use the Start argument as 3.

Code:

Sub INSTR_Example()

  Dim MyValue As String

  MyValue = InStr(3, "Recipe", "e")

  MsgBox MyValue

End Sub

So, in this case, the position of the letter “e” after the first appearance is 6th.

VBA String Functions Example 1

These are some of the important String functions. We hope you have enjoyed it.

Recommended Articles

This article has been a guide to VBA String Functions. Here, we learn a list of the top 6 VBA String functions, including LEN, LEFT, MID, Right, Instr, and Trim, along with examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA Right Function
  • Excel Trim Formula
  • ROUND Formula Excel
  • Worksheet Functions in VBA

На чтение 23 мин. Просмотров 18.4k.

VBA String Functions

Содержание

  1. Краткое руководство по текстовым функциям
  2. Введение
  3. Прочитайте это в первую очередь!
  4. Добавление строк
  5. Извлечение части строки
  6. Поиск в строке
  7. Удаление пробелов
  8. Длина строки
  9. Перевернуть текст
  10. Сравнение
  11. Сравнение строк с использованием сопоставления с шаблоном
  12. Заменить часть строки
  13. Преобразовать типы в строку (базовый)
  14. Преобразовать строку в число — CLng, CDbl, Val и т.д.
  15. Генерация строки элементов — функция строки
  16. Преобразовать регистр / юникод — StrConv, UCase, LCase
  17. Использование строк с массивами
  18. Форматирование строки
  19. Заключение

Краткое руководство по текстовым функциям

Текстовые операции Функции
Добавить две или более строки Format or «&»
Построить текст из массива Join
Сравнить StrComp or «=»
Сравнить — шаблон Like
Преобразовать в текст CStr, Str
Конвертировать текст в дату Просто: CDate 
Дополнительно: Format
Преобразовать текст в число Просто: CLng, CInt, CDbl, Val
Дополнительно: Format
Конвертировать в юникод, широкий, узкий StrConv
Преобразовать в верхний / нижний регистр StrConv, UCase, LCase
Извлечь часть текста Left, Right, Mid
Форматировать текст Format
Найти символы в тексте InStr, InStrRev
Генерация текста String
Получить длину строки Len
Удалить пробелы LTrim, RTrim, Trim
Заменить часть строки Replace
Перевернуть строку StrReverse
Разобрать строку в массив Split

Введение

Использование строк является очень важной частью VBA. Есть много типов манипуляций, которые вы можете делать со строками. К ним относятся такие задачи, как:

  • извлечение части строки
  • сравнение строк
  • преобразование чисел в текст
  • форматирование даты для включения дня недели
  • найти символ в строке
  • удаление пробелов
  • парсинг в массив
  • и т. д.  

Хорошей новостью является то, что VBA содержит множество функций, которые помогут вам легко выполнять эти задачи.

Эта статья содержит подробное руководство по использованию строки в VBA. Он объясняет строки в простых терминах с понятными примерами кода. Изложение в статье поможет легко использовать ее в качестве краткого справочного руководства.

Если вы собираетесь использовать строки часто, я рекомендую вам прочитать первый раздел, так как он относится ко многим функциям. В противном случае вы можете прочитать по порядку или просто перейти в нужный раздел.

Прочитайте это в первую очередь!

Следующие два пункта очень важны при работе со строковыми функциями VBA.

Исходная строка не изменяется

Важно помнить, что строковые функции VBA не изменяют исходную строку. Они возвращают новую строку с изменениями, внесенными функцией. Если вы хотите изменить исходную строку, вы просто назначаете результат исходной строке. См. Раздел «Извлечение части строки» для примеров.

Как использовать Compare

Некоторые строковые функции, такие как StrComp (), Instr () и т.д. имеют необязательный параметр Compare. Он работает следующим образом:

vbTextCompare: верхний и нижний регистры считаются одинаковыми

vbBinaryCompare: верхний и нижний регистр считаются разными

Следующий код использует функцию сравнения строк StrComp () для демонстрации параметра Compare.

Sub Comp1()

    ' Печатает 0  : Строки совпадают
    Debug.Print StrComp("АБВ", "абв", vbTextCompare)
    ' Печатает -1 : Строки не совпадают
    Debug.Print StrComp("АБВ", "абв", vbBinaryCompare)

End Sub

Вы можете использовать параметр Option Compare вместо того, чтобы каждый раз использовать этот параметр. Опция сравнения устанавливается в верхней части модуля. Любая функция, которая использует параметр Compare, примет этот параметр по умолчанию. Два варианта использования Option Compare:

  • Oпция Compare Text: делает vbTextCompare аргументом сравнения по умолчанию
Option Compare Text

Sub Comp2()
    ' Соответствие строк - использует vbCompareText в качестве 'аргумента сравнения
    Debug.Print StrComp("АБВ", "абв")
    Debug.Print StrComp("ГДЕ", "где")
End Sub
  • Опция Compare Binary: делает vbBinaryCompare аргументом сравнения по умолчанию.
Option Compare Binary

Sub Comp2()
    ' Строки не совпадают - использует vbCompareBinary в качестве 'аргумента сравнения
    Debug.Print StrComp("АБВ", "абв")
    Debug.Print StrComp("ГДЕ", "где")
End Sub

Если Option Compare не используется, то по умолчанию используется Option Compare Binary.

Теперь, когда вы понимаете эти два важных момента о строке, мы можем продолжить и посмотреть на строковые функции индивидуально.

Добавление строк

VBA String Functions - Smaller

Вы можете добавлять строки, используя оператор &. Следующий код показывает несколько примеров его использования.

Sub Dobavlenie()

    Debug.Print "АБВ" & "ГДЕ"
    Debug.Print "Иван" & " " & "Петров"
    Debug.Print "Длинный " & 22
    Debug.Print "Двойной " & 14.99
    Debug.Print "Дата " & #12/12/2015#

End Sub

В примере вы можете видеть, что различные типы, такие как даты и числа, автоматически преобразуются в строки. Вы можете увидеть оператор +, используемый для добавления строк. Разница в том, что этот оператор будет работать только со строковыми типами. Если вы попытаетесь использовать его с другим типом, вы получите ошибку.

 Это даст сообщение об ошибке: «Несоответствие типов»
    Debug.Print "Длинный " + 22

Если вы хотите сделать более сложное добавление строк, вы можете использовать функцию форматирования, описанную ниже.

Извлечение части строки

Функции, обсуждаемые в этом разделе, полезны при базовом извлечении из строки. Для чего-то более сложного можете посмотреть раздел, как легко извлечь любую строку без использования VBA InStr.

Функция Параметры Описание Пример
Left строка, длина Вернуть
символы с
левой стороны
Left(«Иван
Петров»,4)
Right строка, длина Вернуть
символы с
правой
стороны
Right(«Иван
Петров»,5)
Mid строка, начало, длина Вернуть
символы из
середины
Mid(«Иван
Петров»,3,2)

Функции Left, Right и Mid используются для извлечения частей строки. Это очень простые в использовании функции. Left читает символы слева, Right справа и Mid от указанной вами начальной точки.

Sub IspLeftRightMid()

    Dim sCustomer As String
    sCustomer = "Иван Васильевич Петров"

    Debug.Print Left(sCustomer, 4)  '  Печатает: Иван
    Debug.Print Right(sCustomer, 6) '  Печатает: Петров

    Debug.Print Left(sCustomer, 15)  '  Печатает: Иван Васильевич
    Debug.Print Right(sCustomer, 17)  '  Печатает: Васильевич Петров

    Debug.Print Mid(sCustomer, 1, 4) ' Печатает: Иван
    Debug.Print Mid(sCustomer, 6, 10) ' Печатает: Васильевич
    Debug.Print Mid(sCustomer, 17, 6) ' Печатает: Петров

End Sub

Как упоминалось в предыдущем разделе, строковые функции VBA не изменяют исходную строку. Вместо этого они возвращают результат в виде новой строки.

В следующем примере вы увидите, что строка Fullname не была изменена после использования функции Left.

Sub PrimerIspolzovaniyaLeft()

    Dim Fullname As String
    Fullname = "Иван Петров"

    Debug.Print "Имя: "; Left(Fullname, 4)
    ' Исходная строка не изменилась
    Debug.Print "Полное имя: "; Fullname

 End Sub

Если вы хотите изменить исходную строку, вы просто присваиваете ей возвращаемое значение функции.

Sub IzmenenieStroki()

    Dim name As String
    name = "Иван Петров"

    ' Присвойте возвращаемую строку переменной имени
    name = Left(name, 4)

    Debug.Print "Имя: "; name

 End Sub

Поиск в строке

Функция Параметры Описание Пример
InStr Текст1,
текст2
Находит
положение
текста
InStr(«Иван
Петров»,»в»)
InStrRev Проверка
текста,
соответствие
текста
Находит
позицию
текста с конца
InStrRev(«Иван Петров»,»в»)

InStr и InStrRev — это функции VBA, используемые для поиска текста в тексте. Если текст поиска найден, возвращается позиция (с начала строки проверки) текста поиска. Когда текст поиска не найден, возвращается ноль. Если какой-либо текст имеет значение null, возвращается значение null.

InStr Описание параметров

InStr() Start[Необязат], String1, String2, Compare[Необязат]

  • Start [Необязательно — по умолчанию 1]: это число, указывающее начальную позицию поиска слева
  • String1: текст, в котором будем искать
  • String2: текст, который будем искать
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

Использование InStr и примеры

InStr возвращает первую позицию в тексте, где найден данный текст. Ниже приведены некоторые примеры его использования.

Sub PoiskTeksta()

    Dim name As String
    name = "Иван Петров"

    ' Возвращает 3 - позицию от первой 
    Debug.Print InStr(name, "а")
    ' Возвращает 10 - позиция первого "а", начиная с позиции 4
    Debug.Print InStr(4, name, "а")
    ' Возвращает 8
    Debug.Print InStr(name, "тр")
    ' Возвращает 6
    Debug.Print InStr(name, "Петров")
    ' Возвращает 0 - текст "ССС" не найдет
    Debug.Print InStr(name, "ССС")

End Sub

InStrRev Описание параметров

InStrRev() StringCheck, StringMatch, Start[Необязат], Compare[Необязат]

  • StringCheck: текст, в котором будем искать
  • StringMatch: Текст, который будем искать
  • Start [Необязательно — по умолчанию -1]: это число, указывающее начальную позицию поиска справа
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

Использование InStrRev и примеры

Функция InStrRev такая же, как InStr, за исключением того, что она ищет с конца строки. Важно отметить, что возвращаемая позиция является позицией с самого начала. Поэтому, если существует только один экземпляр элемента поиска, InStr () и InStrRev () будут возвращать одно и то же значение.

В следующем коде показаны некоторые примеры использования InStrRev.

Sub IspInstrRev()

    Dim name As String
    name = "Иван Петров"

    ' Обе возвращают 1 - позицию, только И
    Debug.Print InStr(name, "И")
    Debug.Print InStrRev(name, "И")

    ' Возвращает 11 - вторую в
    Debug.Print InStrRev(name, "в")
    ' Возвращает 3 - первую в с позиции 9
    Debug.Print InStrRev(name, "в", 9)

    ' Returns 1
    Debug.Print InStrRev(name, "Иван")

End Sub

Функции InStr и InStrRev полезны при работе с базовым поиском текста. Однако, если вы собираетесь использовать их для извлечения текста из строки, они могут усложнить задачу. Я написал о гораздо лучшем способе сделать это в своей статье Как легко извлечь любой текст без использования VBA InStr.

Удаление пробелов

Функция Параметры Описание Пример
LTrim Текст Убирает
пробелы слева
LTrim(» Иван «)
RTrim Текст Убирает
пробелы
справа
RTrim(» Иван «)
Trim Текст Убирает
пробелы слева и справа
Trim(» Иван «)

Функции Trim — это простые функции, которые удаляют пробелы в начале или конце строки.

Функции и примеры использования триммера Trim

  • LTrim удаляет пробелы слева от строки
  • RTrim удаляет пробелы справа от строки
  • Trim удаляет пробелы слева и справа от строки
Sub TrimStr()

    Dim name As String
    name = "  Иван Петров  "

    ' Печатает "Иван Петров  "
    Debug.Print LTrim(name)
    ' Печатает "  Иван Петров"
    Debug.Print RTrim(name)
    ' Печатает "Иван Петров"
    Debug.Print Trim(name)

End Sub

Длина строки

Функция Параметры Описание Пример
Len Текст Возвращает
длину строки
Len («Иван Петров»)

Len — простая функция при использовании со строкой. Она просто возвращает количество символов, которое содержит строка. Если используется с числовым типом, таким как long, он вернет количество байтов.

Sub IspLen()

    Dim name As String
    name = "Иван Петров"

    ' Печатает 11
    Debug.Print Len("Иван Петров")
    ' Печатает 3
    Debug.Print Len("АБВ")

    ' Печатает 4 с Long - это размер 4 байта
    Dim total As Long
    Debug.Print Len(total)

End Sub

Перевернуть текст

Функция Параметры Описание Пример
StrReverse Текст Перевернуть
текст
StrReverse
(«Иван
Петров»)

StrReverse — еще одна простая в использовании функция. Он просто возвращает данную строку с обратными символами.

Sub RevStr()

    Dim s As String
    s = "Иван Петров"
    ' Печатает: вортеП навИ
    Debug.Print StrReverse(s)

End Sub

Сравнение

Функция Параметры Описание Пример
StrComp Текст1, текст2 Сравнивает 2
текста
StrComp
(«Иван»,
«Иван»)

Функция StrComp используется для сравнения двух строк. Следующие подразделы описывают, как используется.

Описание параметров

StrComp()  String1, String2, Compare[Необязат]

  • String1: первая строка для сравнения
  • String2: вторая строка для сравнения
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

StrComp Возвращаемые значения

Возвращаемое значение Описание
0 Совпадение строк
-1 строка1 меньше строки2
1 строка1 больше строки2
Null если какая-либо строка равна нулю

Использование и примеры

Ниже приведены некоторые примеры использования функции StrComp.

Sub IspStrComp()

   ' Возвращает  0
   Debug.Print StrComp("АБВ", "АБВ", vbTextCompare)
   ' Возвращает 1
   Debug.Print StrComp("АБВГ", "АБВ", vbTextCompare)
   ' Возвращает -1
   Debug.Print StrComp("АБВ", "АБВГ", vbTextCompare)
   ' Returns Null
   Debug.Print StrComp(Null, "АБВГ", vbTextCompare)

End Sub

Сравнение строк с использованием операторов

Вы также можете использовать знак равенства для сравнения строк. Разница между сравнением equals и функцией StrComp:

  1. Знак равенства возвращает только true или false.
  2. Вы не можете указать параметр Compare, используя знак равенства — он использует настройку «Option Compare».  

Ниже приведены некоторые примеры использования equals для сравнения строк.

Option Compare Text

Sub CompareIspEquals()

    ' Возвращает true
    Debug.Print "АБВ" = "АБВ"
    ' Возвращает true, потому что «Сравнить текст» установлен выше
    Debug.Print "АБВ" = "абв"
    ' Возвращает false
    Debug.Print "АБВГ" = "АБВ"
    ' Возвращает false
    Debug.Print "АБВ" = "АБВГ"
    ' Возвращает null
    Debug.Print Null = "АБВГ"

End Sub

Сравнение строк с использованием сопоставления с шаблоном

Функция Параметры Описание Пример
Like Текст, шаблон проверяет, имеет
ли строка
заданный
шаблон
«abX» Like «??X»
«54abc5» Like «*abc#»
Знак Значение
? Любой одиночный символ
# Любая однозначная цифра (0-9)
* Ноль или более символов
[charlist] Любой символ в списке
[!charlist] Любой символ не в списке символов

Сопоставление с шаблоном используется для определения того, имеет ли строка конкретный образец символов. Например, вы можете проверить, что номер клиента состоит из 3 цифр, за которыми следуют 3 алфавитных символа, или в строке есть буквы XX, за которыми следует любое количество символов.

Если строка соответствует шаблону, возвращаемое значение равно true, в противном случае — false.

Сопоставление с образцом аналогично функции формата VBA в том смысле, что его можно использовать практически безгранично. В этом разделе я приведу несколько примеров, которые объяснят, как это работает. Это должно охватывать наиболее распространенные виды использования.

Давайте посмотрим на базовый пример с использованием знаков. Возьмите следующую строку шаблона.

[abc][!def]?#X*

 Давайте посмотрим, как работает эта строка

[abc] — символ, который является или a, b или c
[! def] — символ, который не является d, e или f
? любой символ
# — любая цифра
X — символ X
* следуют ноль или более символов

 Поэтому следующая строка действительна
apY6X

а — один из символов a,b,c
p — не один из символов d, e или f
Y — любой символ
6 — это цифра
Х — это буква Х

В следующих примерах кода показаны результаты различных строк с этим шаблоном.

Sub Shabloni()

    ' ИСТИНА
    Debug.Print 1; "apY6X" Like "[abc][!def]?#X*"
    ' ИСТИНА - любая комбинация символов после x действительна
    Debug.Print 2; "apY6Xsf34FAD" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - символ не из[abc]
    Debug.Print 3; "dpY6X" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - 2-й символ e находится в [def]
    Debug.Print 4; "aeY6X" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - A в позиции 4 не является цифрой
    Debug.Print 5; "apYAX" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - символ в позиции 5 должен быть X
    Debug.Print 1; "apY6Z" Like "[abc][!def]?#X*"

End Sub

Реальный пример сопоставления с образцом

Чтобы увидеть реальный пример использования сопоставления с образцом, ознакомьтесь с Примером 3: Проверьте, допустимо ли имя файла.

Важное примечание о сопоставлении с образцом VBA

Оператор Like использует двоичное или текстовое сравнение на основе параметра Option Compare. Пожалуйста, смотрите раздел Сравнение для более подробной информации.

Заменить часть строки

Функция Параметры Описание Пример
Replace строка, найти, заменить,
начать,
считать,
сравнивать
Заменяет текст Replace
(«Ива»,»а»,»ан»)

Replace используется для замены текста в строке другим текстом. Он заменяет все экземпляры текста, найденные по умолчанию.

Replace описание параметров

Replace()  Expression, Find, Replace, Start[Необязат], Count[Необязат], Compare[Необязат]

  • Expression: текст, в котором нужна замена символов
  • Find: текст для замены в строке выражения
  • Replace: строка для поиска замены текста поиска
  • Start [Необязательно — по умолчанию 1]: начальная позиция в строке
  • Count [Необязательно — по умолчанию -1]: количество замен. По умолчанию -1 означает все.
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

Использование и примеры

В следующем коде показаны некоторые примеры использования функции замены.

Sub PrimeriReplace()

    ' Заменяет все знаки вопроса (?) на точку с запятой (;)
    Debug.Print Replace("A?B?C?D?E", "?", ";")
    ' Заменить Петров на Иванов
    Debug.Print Replace("Евгений Петров,Артем Петров", "Петров", "Иванов")
    ' Заменить AX на AB
    Debug.Print Replace("ACD AXC BAX", "AX", "AB")

End Sub

На выходе:

A;B;C;D;E
Евгений Иванов,Артем Иванов
ACD ABC BAB

В следующих примерах мы используем необязательный параметр Count. Count определяет количество замен. Так, например, установка Count равной единице означает, что будет заменено только первое вхождение.

Sub ReplaceCount()

    ' Заменяет только первый знак вопроса
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=1)
    ' Заменяет первые три знака вопроса
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=3)

End Sub

На выходе:

A;B?C?D?E
A;B;C;D?E

Необязательный параметр Start позволяет вам вернуть часть строки. Позиция, которую вы указываете с помощью Start, — это место, откуда начинается возврат строки. Он не вернет ни одной части строки до этой позиции, независимо от того, была ли произведена замена или нет.

Sub ReplacePartial()

    ' Использовать оригинальную строку из позиции 4
    Debug.Print Replace("A?B?C?D?E", "?", ";", Start:=4)
    ' Используйте оригинальную строку из позиции 8
    Debug.Print Replace("AA?B?C?D?E", "?", ";", Start:=8)
    ' Элемент не заменен, но по-прежнему возвращаются только последние '2 символа
    Debug.Print Replace("ABCD", "X", "Y", Start:=3)

End Sub

На выходе:

;C;D;E
;E
CD

Иногда вы можете заменить только заглавные или строчные буквы. Вы можете использовать параметр Compare для этого. Он используется во многих строковых функциях. Для получения дополнительной информации об этом проверьте раздел сравнения.

Sub ReplaceCase()

    ' Заменить только заглавные А
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbBinaryCompare)
    ' Заменить все А
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbTextCompare)

End Sub

На выходе:

XaXa
XXXX

Многократные замены

Если вы хотите заменить несколько значений в строке, вы можете вкладывать вызовы. В следующем коде мы хотим заменить X и Y на A и B соответственно.

Sub ReplaceMulti()

    Dim newString As String

    ' Заменить А на Х
    newString = Replace("ABCD ABDN", "A", "X")
    ' Теперь замените B на Y в новой строке
    newString = Replace(newString, "B", "Y")

    Debug.Print newString

End Sub

В следующем примере мы изменим приведенный выше код для выполнения той же задачи. Мы будем использовать возвращаемое значение первой замены в качестве аргумента для второй замены.

Sub ReplaceMultiNested()

    Dim newString As String

    ' Заменить A на X, а B на Y
    newString = Replace(Replace("ABCD ABDN", "A", "X"), "B", "Y")

    Debug.Print newString

End Sub

Результатом обоих этих Subs является:
XYCD XYDN

Преобразовать типы в строку (базовый)

Этот раздел о преобразовании чисел в строку. Очень важным моментом здесь является то, что в большинстве случаев VBA автоматически конвертируется в строку для вас. Давайте посмотрим на некоторые примеры:

Sub AutoConverts()

    Dim s As String
    ' Автоматически преобразует число в строку
    s = 12.99
    Debug.Print s

    ' Автоматически преобразует несколько чисел в строку
    s = "ABC" & 6 & 12.99
    Debug.Print s

    ' Автоматически преобразует двойную переменную в строку
    Dim d As Double, l As Long
    d = 19.99
    l = 55
    s = "Значения: " & d & " " & l
    Debug.Print s

End Sub

Когда вы запустите приведенный выше код, вы увидите, что число было автоматически преобразовано в строки. Поэтому, когда вы присваиваете значение строке, VBA будет следить за преобразованием большую часть времени. В VBA есть функции преобразования, и в следующих подразделах мы рассмотрим причины их использования.

Явное преобразование

Функция Параметры Описание Пример
CStr выражение Преобразует
числовую
переменную
в строку
CStr («45.78»)
Str число Преобразует
числовую
переменную
в строку
Str («45.78»)

В некоторых случаях вы можете захотеть преобразовать элемент в строку без необходимости сначала помещать его в строковую переменную. В этом случае вы можете использовать функции Str или CStr. Оба принимают выражение как функцию, и это может быть любой тип, например long, double, data или boolean.

Давайте посмотрим на простой пример. Представьте, что вы читаете список значений из разных типов ячеек в коллекцию. Вы можете использовать функции Str / CStr, чтобы гарантировать, что они все хранятся в виде строк. Следующий код показывает пример этого:

Sub IspStr()

    Dim coll As New Collection
    Dim c As Range

    ' Считать значения ячеек в коллекцию
    For Each c In Range("A1:A10")
        ' Используйте Str для преобразования значения ячейки в строку
        coll.Add Str(c)
    Next

    ' Распечатайте значения и тип коллекции
    Dim i As Variant
    For Each i In coll
        Debug.Print i, TypeName(i)
    Next

End Sub

В приведенном выше примере мы используем Str для преобразования значения ячейки в строку. Альтернативой этому может быть присвоение значения строке, а затем присвоение строки коллекции. Итак, вы видите, что использование Str здесь намного эффективнее.

Multi Region

Разница между функциями Str и CStr заключается в том, что CStr преобразует в зависимости от региона. Если ваши макросы будут использоваться в нескольких регионах, вам нужно будет использовать CStr для преобразования строк.

Хорошей практикой является использование CStr при чтении значений из ячеек. Если ваш код в конечном итоге используется в другом регионе, вам не нужно вносить какие-либо изменения, чтобы он работал правильно.

Преобразовать строку в число — CLng, CDbl, Val и т.д.

Функция Возвращает Пример
CBool Boolean CBool(«True»), CBool(«0»)
CCur Currency CCur(«245.567»)
CDate Date CDate(«1/1/2019»)
CDbl Double CDbl(«245.567»)
CDec Decimal CDec(«245.567»)
CInt Integer CInt(«45»)
CLng Long Integer CLng(«45.78»)
CVar Variant CVar(«»)

Вышеуказанные функции используются для преобразования строк в различные типы. Если вы присваиваете переменную этого типа, VBA выполнит преобразование автоматически.

Sub StrToNumeric()

    Dim l As Long, d As Double, c As Currency
    Dim s As String
    s = "45.923239"

    l = s
    d = s
    c = s

    Debug.Print "Long is "; l
    Debug.Print "Double is "; d
    Debug.Print "Currency is "; c

End Sub

Использование типов преобразования дает большую гибкость. Это означает, что вы можете определить тип во время выполнения. В следующем коде мы устанавливаем тип на основе аргумента sType, передаваемого в функцию PrintValue. Поскольку этот тип может быть прочитан из внешнего источника, такого как ячейка, мы можем установить тип во время выполнения. Если мы объявим переменную как Long, то при выполнении кода она всегда будет длинной.

Sub Test()
    ' Печатает  46
    PrintValue "45.56", "Long"
    ' Печатает 45.56
    PrintValue "45.56", ""
End Sub

Sub PrintValue(ByVal s As String, ByVal sType As String)

    Dim value

    ' Установите тип данных на основе строки типа
    If sType = "Long" Then
        value = CLng(s)
    Else
        value = CDbl(s)
    End If
    Debug.Print "Type is "; TypeName(value); value

End Sub

Если строка не является допустимым числом (т.е. Содержит символы, другие цифры), вы получаете ошибку «Несоответствие типов».

Sub InvalidNumber()

    Dim l As Long

    ' Даст ошибку несоответствия типов
    l = CLng("45A")

End Sub

Функция Val

Функция преобразует числовые части строки в правильный тип числа.

Val преобразует первые встреченные числа. Как только он встречает буквы в строке, он останавливается. Если есть только буквы, то в качестве значения возвращается ноль. Следующий код показывает некоторые примеры использования Val

Sub IspVal()

    ' Печатает 45
    Debug.Print Val("45 Новая улица")

    ' Печатает 45
    Debug.Print Val("    45 Новая улица")

    ' Печатает 0
    Debug.Print Val("Новая улица 45")

    ' Печатает 12
    Debug.Print Val("12 f 34")

End Sub

Val имеет два недостатка

  1. Не мультирегиональный — Val не распознает международные версии чисел, такие как запятые вместо десятичных. Поэтому вы должны использовать вышеуказанные функции преобразования, когда ваше приложение будет использоваться в нескольких регионах.
  2. Преобразует недопустимые строки в ноль — в некоторых случаях это может быть нормально, но в большинстве случаев лучше, если неверная строка вызывает ошибку. Затем приложение осознает наличие проблемы и может действовать соответствующим образом. Функции преобразования, такие как CLng, вызовут ошибку, если строка содержит нечисловые символы.

Генерация строки элементов — функция строки

Функция Параметры Описание Пример
String число, символ Преобразует
числовую
переменную
в строку
String (5,»*»)

Функция String используется для генерации строки повторяющихся символов. Первый аргумент — это количество повторений, второй аргумент — символ.

Sub IspString()

    ' Печатает: AAAAA
    Debug.Print String(5, "A")
    ' Печатает: >>>>>
    Debug.Print String(5, 62)
    ' Печатает: (((ABC)))
    Debug.Print String(3, "(") & "ABC" & String(3, ")")

End Sub

Преобразовать регистр / юникод — StrConv, UCase, LCase

Функция Параметры Описание Пример
StrConv строка,
преобразование, LCID
Преобразует
строку
StrConv(«abc»,vbUpperCase)

Если вы хотите преобразовать регистр строки в верхний или нижний регистр, вы можете использовать функции UCase и LCase для верхнего и нижнего соответственно. Вы также можете использовать функцию StrConv с аргументом vbUpperCase или vbLowerCase. В следующем коде показан пример использования этих трех функций.

Sub ConvCase()

    Dim s As String
    s = "У Мэри был маленький ягненок"

    ' верхний
    Debug.Print UCase(s)
    Debug.Print StrConv(s, vbUpperCase)

    ' нижний
    Debug.Print LCase(s)
    Debug.Print StrConv(s, vbLowerCase)

    ' Устанавливает первую букву каждого слова в верхний регистр
    Debug.Print StrConv(s, vbProperCase)

End Sub

На выходе: 

У МЭРИ БЫЛ МАЛЕНЬКИЙ ЯГНЕНОК
У МЭРИ БЫЛ МАЛЕНЬКИЙ ЯГНЕНОК
у мэри был маленький ягненок
у мэри был маленький ягненок
У Мэри Был Маленький Ягненок

Другие преобразования

Как и в случае, StrConv может выполнять другие преобразования на основе параметра Conversion. В следующей таблице приведен список различных значений параметров и того, что они делают. Для получения дополнительной информации о StrConv проверьте страницу MSDN.

Постоянные Преобразует Значение
vbUpperCase 1 в верхний регистр
vbLowerCase 2 в нижнем регистре
vbProperCase 3 первая буква
каждого слова в
верхнем регистре
vbWide* 4 от узкого к
широкому
vbNarrow* 8 от широкого к
узкому
vbKatakana** 16 из Хираганы в
Катакану
vbHiragana 32 из Катаканы в
Хирагану
vbUnicode 64 в юникод
vbFromUnicode 128 из юникода

Использование строк с массивами

Функция Параметры Описание Пример
Split выражение,
разделитель,
ограничить,
сравнить
Разбирает
разделенную
строку в
массив
arr = Split(«A;B;C»,»;»)
Join исходный
массив,
разделитель
Преобразует
одномерный
массив в
строку
s = Join(Arr, «;»)

Строка в массив с использованием Split

Вы можете легко разобрать строку с разделителями в массив. Вы просто используете функцию Split с разделителем в качестве параметра. Следующий код показывает пример использования функции Split.

Sub StrToArr()

    Dim arr() As String
    ' Разобрать строку в массив
    arr = Split("Иван,Анна,Павел,София", ",")

    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

На выходе:

Иван
Анна
Павел
София

Если вы хотите увидеть некоторые реальные примеры использования Split, вы найдете их в статье Как легко извлечь любую строку без использования VBA InStr.

Массив в строку, используя Join

Если вы хотите построить строку из массива, вы можете легко это сделать с помощью функции Join. По сути, это обратная функция Split. Следующий код предоставляет пример использования Join

Sub ArrToStr()

    Dim Arr(0 To 3) As String
    Arr(0) = "Иван"
    Arr(1) = "Анна"
    Arr(2) = "Павел"
    Arr(3) = "София"

    ' Построить строку из массива
    Dim sNames As String
    sNames = Join(Arr, ",")

    Debug.Print sNames

End Sub

На выходе:

Иван, Анна, Павел, София

Форматирование строки

Функция Параметры Описание Пример
Format выражение,
формат,
firstdayofweek,
firstweekofyear
Форматирует
строку
Format(0.5, «0.00%»)

Функция Format используется для форматирования строки на основе заданных инструкций. В основном используется для размещения даты или числа в определенном формате. Приведенные ниже примеры показывают наиболее распространенные способы форматирования даты.

Sub FormatDate()

    Dim s As String
    s = "31/12/2019 10:15:45"

    ' Печатает: 31 12 19
    Debug.Print Format(s, "DD MM YY")
    ' Печатает: Thu 31 Dec 2019
    Debug.Print Format(s, "DDD DD MMM YYYY")
    ' Печатает: Thursday 31 December 2019
    Debug.Print Format(s, "DDDD DD MMMM YYYY")
    ' Печатает: 10:15
    Debug.Print Format(s, "HH:MM")
    ' Печатает: 10:15:45 AM
    Debug.Print Format(s, "HH:MM:SS AM/PM")

End Sub

В следующих примерах представлены некоторые распространенные способы форматирования чисел.

Sub FormatNumbers()

    ' Печатает: 50.00%
    Debug.Print Format(0.5, "0.00%")
    ' Печатает: 023.45
    Debug.Print Format(23.45, "00#.00")
    ' Печатает: 23,000
    Debug.Print Format(23000, "##,000")
    ' Печатает: 023,000
    Debug.Print Format(23000, "0##,000")
    ' Печатает: $23.99
    Debug.Print Format(23.99, "$#0.00")

End Sub

Функция «Формат» — довольно обширная тема, и она может самостоятельно занять всю статью. Если вы хотите получить больше информации, то страница формата MSDN предоставляет много информации.

Полезный совет по использованию формата

Быстрый способ выяснить используемое форматирование — использовать форматирование ячеек на листе Excel. Например, добавьте число в ячейку. Затем щелкните правой кнопкой мыши и отформатируйте ячейку так, как вам нужно. Если вы довольны форматом, выберите «Пользовательский» в списке категорий слева. При выборе этого вы можете увидеть строку формата в текстовом поле типа. Это формат строки, который вы можете использовать в VBA.

VBA Format Function

Заключение

Практически в любом типе программирования вы потратите много времени на манипулирование строками. В этой статье рассматриваются различные способы использования строк в VBA.

Чтобы получить максимальную отдачу, используйте таблицу вверху, чтобы найти тип функции, которую вы хотите использовать. Нажав на левую колонку этой функции, вы попадете в этот раздел.

Если вы новичок в строках в VBA, то я предлагаю вам ознакомиться с разделом «Прочтите это в первую очередь» перед использованием любой из функций.

The String data type represents text. A string is an array of characters. VBA strings use 16-bit Unicode characters. VBA has a built-in Strings module with functions for manipulating strings. Efficiency is an important topic when it comes to dealing with strings.

String Literals

String literals are used to represent strings in code. Text surrounded by double quotes represents a string literal in VBA.

Public Sub Example()

    Debug.Print "Hello, World!" 'Prints: Hello, World!

End Sub

To create a string literal that contains double quotes, use double double quotes.

Public Sub Example()

    Debug.Print "Hello, World!"       'Prints: Hello, World!

    Debug.Print """Hello, World!"""   'Prints: "Hello, World!"

    Debug.Print "Hello, ""World""!"   'Prints: Hello, "World"!

    Debug.Print """"                  'Prints: "

    Debug.Print """"""                'Prints: ""

End Sub

String Type Conversion

To explicitly convert a value to a string use the CStr function. The Str function can be used to convert a number to a string. The Str function only recognizes the period as a decimal place, so when working with international numbers where the decimal may be a comma, use the CStr function.

Public Sub Example()

    Dim S As String

    S = CStr(350)         ' -> "350"

    S = CStr(3.5)         ' -> "3.5"

    S = CStr(True)        ' -> "True"

    S = CStr(#1/1/2021#)  ' -> "1/1/2021"

    S = CStr(3.5@)        ' -> "3.5"

End Sub

String Concatenation

Both the & and + operators can be used to concatenate strings in VBA. Using the & operator will implicitly convert non-string values to strings. Using the + operator will not implicitly convert non-strings to strings. Trying to concatenate a string value with a non-string value using + will cause a type mismatch error. The CStr function can be used to explicitly convert non-string values to strings. There is no significant difference in speed between using & and +.

Public Sub Example()

    Debug.Print "Hello, " + "World!"

    'Debug.Print "Hello, " + 1 'Causes Error

    Debug.Print "Hello, " + Cstr(1)

End Sub

Public Sub Example()

    Debug.Print "Hello, " & "World!"

    Debug.Print "Hello, " & 1

    Debug.Print "Hello, " & Cstr(1) 'Not necessary to use CStr with &

End Sub

Variable-Length Strings

Variable-Length Strings can hold a large number of characters (2 ^ 31). The size of a Variable-Length String is determined by the number of characters in the String. The Len and LenB functions can be used to return the number of characters and bytes respectively in a String.

Public Sub Example()

    Dim S As String

    S = "Hello, World!"

    Debug.Print S

    Debug.Print Len(S)
    Debug.Print LenB(S)

End Sub

Fixed-Length Strings

Fixed-length strings are given a specific length at design-time when they are declared which cannot be altered at run-time. When a string is too long to fit in the fixed-length string it will be truncated. When a string is shorter than the fixed-length string the remaining space will be set to space characters (Chr 32). An uninitialized fixed-length string will be all null characters (Chr 0) for the length of the string. Fixed-Length strings can store from 1 to 65,535 characters. The Len and LenB functions can be used to get the length of a string in terms of characters and bytes respectively.

Public Sub Example()

    Dim S As String * 10

    S = "Hello, World!"
    Debug.Print """" & S & """" 'Prints: "Hello, Wor"

    S = "ABCD"
    Debug.Print """" & S & """" 'Prints: "ABCD      "

    Debug.Print Len(S)
    Debug.Print LenB(S)

End Sub

Byte Arrays

Byte arrays and Strings are interchangeable. Byte Arrays can be assigned directly to Strings and Strings can be assigned directly to Byte Arrays.

Public Sub Example()

    Dim S As String
    S = "Hello, World!"

    Dim Arr() As Byte
    Arr = S

    Debug.Print Arr

End Sub

VBA Strings use two bytes to store each character so every two bytes in a byte array represents one character. Most common characters only require one byte to store and thus the second byte will be zero.

Public Sub Example()

    Dim Arr(0 To 9) As Byte
    Arr(0) = 72
    Arr(1) = 0
    Arr(2) = 101
    Arr(3) = 0
    Arr(4) = 108
    Arr(5) = 0
    Arr(6) = 108
    Arr(7) = 0
    Arr(8) = 111
    Arr(9) = 0

    Debug.Print Arr 'Prints: Hello

End Sub

String Comparison

Strings can be compared using comparison operators or the StrComp function.

Comparison Operators

Strings can be compared in VBA using comparison operators: =, >, <, >=, <=, <>, Like. Comparing strings using comparison operators will return True or False. The compare method used to compare strings when using comparison operators is determined by the Option Compare statement. The Option Compare statement can specify Binary or Text. Binary comparison compares the binary representations of each character. Because the binary representations of uppercase and lowercase characters differ, binary comparison is case-sensitive. Text comparison compares characters using the case-insensitive sort order determined by the system’s locale. In Microsoft Access, Database comparison can be used to compare strings based on the sort order given the locale ID of the database where strings are being compared. If no Option Compare statement is specified the default comparison method is Binary comparison.

Option Compare Binary

Public Sub Example()
    Debug.Print "A" = "a" 'Prints: False
End Sub

Option Compare Text

Public Sub Example()
    Debug.Print "A" = "a" 'Prints: True
End Sub

StrComp Function

The StrComp function can be used to compare two strings. The function takes two string arguments and an optional compare method argument (vbBinaryCompare, vbDatabaseCompare, or vbTextCompare). If no compare argument is specified then the Option Compare statement determines the compare method. The function can return 1, 0, -1, or Null depending on the result of the comparison. The StrComp function is the most explicit way to compare strings because the function can take the compare method as an explicit argument instead of relying on the Option Compare statement.

Syntax: StrComp(string1, string2, [compare])

Result Return Value
string1 < string2 -1
string1 = string2 0
string1 > string2 1
string1 = Null Or string2 = Null Null
Public Sub Example()

    Debug.Print StrComp("A", "a", vbTextCompare) = 0 'Prints: True

End Sub

Mid

The Mid function can be used to retrieve sections of a string, iterate over each individual character in a string, and to assign sections of a string without reallocating an entirely new string. Using Mid to alter strings is faster than allocating new strings.

Public Sub Example()

    Dim S As String

    S = "Hello, World!"

    'Get slice of string
    Debug.Print Mid$(S, 1, 2)

    'Loop over each character
    Dim i As Long
    For i = 1 To Len(S)
        Debug.Print Mid$(S, i, 1)
    Next i

    'Reassign character
    Mid(S, 1, 1) = "A"
    Debug.Print S 'Prints: Aello, World!

End Sub

StrConv

The StrConv function can be used to convert a string’s case and encoding.

Constant Value Description
vbUpperCase 1 Converts the string to uppercase characters.
vbLowerCase 2 Converts the string to lowercase characters.
vbProperCase 3 Converts the first letter of every word in a string to uppercase.
vbWide* 4 Converts narrow (single-byte) characters in a string to wide (double-byte) characters.
vbNarrow* 8 Converts wide (double-byte) characters in a string to narrow (single-byte) characters.
vbKatakana** 16 Converts Hiragana characters in a string to Katakana characters.
vbHiragana** 32 Converts Katakana characters in a string to Hiragana characters.
vbUnicode 64 Converts the string to Unicode using the default code page of the system. (Not available on the Macintosh.)
vbFromUnicode 128 Converts the string from Unicode to the default code page of the system. (Not available on the Macintosh.)

*Applies to East Asia locales. **Applies to Japan only.

Public Sub Example()

    Debug.Print StrConv("hello, world!", vbProperCase) 'Prints: Hello, World!

End Sub

Public Sub Example()

    Dim Arr(0 To 4) As Byte
    Arr(0) = 72
    Arr(1) = 101
    Arr(2) = 108
    Arr(3) = 108
    Arr(4) = 111

    Debug.Print StrConv(Arr, vbUnicode) 'Prints: Hello

End Sub

LSet and Rset

LSet and RSet can be used to assign strings while aligning the text to the left or right of the string. LSet and RSet are used with fixed-length strings and strings that are already assigned so that they have a specific length. There is some performance improvement using LSet and RSet compared to normal string assignment. Any unassigned characters will be filled with space characters. If the string is longer than the string variable it will be truncated.

Public Sub Example()

    Dim S As String
    S = Space$(10)

    LSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "Hello     "

    RSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "     Hello"

End Sub

Public Sub Example()

    Dim S As String * 10

    LSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "Hello     "

    RSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "     Hello"

End Sub

Cleaning Text

Text may contain characters that need to be removed. Extra spaces, non-printable characters, non-breaking spaces, and new line characters are some examples of characters that may need to be removed from text.

Trimming Text

The Trim functions can be used to remove leading spaces, trailing spaces, or both from a string.

Public Sub Example()

    Dim S As String
    S = "   Hello, World!   "

    Debug.Print """" & LTrim$(S) & """" 'Prints: "Hello, World!   "

    Debug.Print """" & RTrim$(S) & """" 'Prints: "   Hello, World!"

    Debug.Print """" & Trim$(S) & """"  'Prints: "Hello, World!"

End Sub

The VBA Trim function does not remove extra consecutive spaces in the middle of a String. To accomplish this, use a user-defined function.

Public Function TrimAll(S As String) As String

    TrimAll = Trim$(S)

    Do While InStr(TrimAll, "  ") > 0
        TrimAll = Replace(TrimAll, "  ", " ")
    Loop

End Function

Remove Non-Printable Characters

Any character in the ASCII table with a value less than 32 is a non-printable character. Thus, to remove non-printable characters, remove all characters with an ASCII value less than 32.

Public Function RemoveNonPrintableCharacters(S As String) As String

    Dim OutString As String
    Dim CurrentCharacter As String * 1
    Dim i As Long
    Dim j As Long

    OutString = Space$(Len(S))

    For i = 1 To Len(S)

        CurrentCharacter = Mid$(S, i, 1)

        If Asc(CurrentCharacter) > 31 Then
            j = j + 1
            Mid$(OutString, j, 1) = CurrentCharacter
        End If

        RemoveNonPrintableCharacters = Left$(OutString, j)

    Next i

End Function

Non-Breaking Spaces

Non-breaking spaces can cause issues when processing text input. Non-breaking spaces appear the same as normal spaces when displayed but they are not the same character. Normal spaces have the value 32 in the ASCII table whereas non-breaking spaces have the value 160 in the ASCII table. It is often beneficial when working with text data to replace non-breaking spaces with normal spaces before doing any other processing on the text.

Public Function ReplaceNonBreakingSpaces(S As String) As String

    ReplaceNonBreakingSpaces = Replace(S, Chr(160), Chr(32))

End Function

New Line Characters

New line characters can cause issues with processing text input. It is common when processing text input to replace new line characters with a space character. Depending on the source of the text there could be different new line characters which must be handled in a particular order.

Public Function ReplaceNewLineCharacters( _
S As String, Optional Replacement As String = " ") As String

    ReplaceNewLineCharacters = _
        Replace(S, vbCrLf, Replacement)

    ReplaceNewLineCharacters = _
        Replace(ReplaceNewLineCharacters, vbLf, Replacement)

    ReplaceNewLineCharacters = _
        Replace(ReplaceNewLineCharacters, vbCr, Replacement)

End Function

Formatting Functions

VBA provides useful built-in functions for formatting text.

Format function

The Format/Format$ function is used to format dates, numbers, and strings according to a user-defined or predefined format. Use the $ version of the function to explicitly return a String instead of a Variant/String.

Public Sub Example()

    '''Dates
    Debug.Print Format$(Now, "mm/dd/yyyy")
    Debug.Print Format$(Now, "Short Date")
    Debug.Print Format$(Now, "mmmm d, yyyy")
    Debug.Print Format$(Now, "Long Date")
    Debug.Print Format$(Now, "Long Time")

    '''Numbers
    Debug.Print Format$(2147483647, "#,##0")
    Debug.Print Format$(2147483647, "Standard")
    Debug.Print Format$(2147483647, "Scientific")

    '''Strings
    'Fill from right to left
    Debug.Print Format$("ABCD", "'@@_@@_@@'")

    'Fill from left to right
    Debug.Print Format$("ABCD", "!'@@_@@_@@'")

    'Lower case
    Debug.Print Format$("ABCD", "<'@@_@@_@@'")

    'Upper case
    Debug.Print Format$("ABCD", ">'@@_@@_@@'")

    'No spaces for missing characters
    Debug.Print Format$("ABCD", "'&&_&&_&&'")

    'Escape double quotes
    Debug.Print Format$("ABCD", "!""@@_@@_@@""")

End Sub

Number Formats

To retrieve a string representing a number in a specific format use one of the number format functions.

Function Description
FormatCurrency Returns a formatted currency as a string using the currency symbol defined in the system control panel.
FormatDateTime Returns a formatted date as string.
FormatNumber Returns a formatted number as a string.
FormatPercent Returns a formatted percentage as a string.

Character Constants

Character Constants are constants used to represent certain special characters. Character constants are defined in the built-in VBA.Constants module.

VBA Constant Character Code Description
vbCr 13 Carriage Return
vbLf 10 Line Feed
vbCrLf 13 + 10 Carriage Return + Line Feed
vbNewLine vbCrLf on Windows or vbLf on Mac New Line Character for current platform
vbNullChar 0 Null Character
vbNullString N/A String pointer to null. vbNullString is equal to an empty string («») when compared but they are different. vbNullString takes less memory because it is only a pointer to null. An empty string is a string with its own location allocated in memory. vbNullString is clearer in meaning than an empty string and should generally be preferred. However, vbNullString cannot be passed to DLLs. Empty strings must be passed to DLLs instead.
vbTab 9 Tab Character
vbBack 8 Backspace Character
vbFormFeed 12 Not useful on Windows or Mac.
vbVerticalTab 11 Not useful on Windows or Mac.

Built-in Strings Module Functions

Member Description
Asc Returns the character code of the first letter in a string.
AscB Returns the first byte of a string.
AscW Returns the Unicode character code when Unicode is supported. If Unicode is not supported it works the same as Asc. *Do not use on Mac. **AscW only Works properly up to 32767 and then returns negative numbers. This problem occurs because Unicode characters are represented by unsigned 16-bit integers and VBA uses signed 16-bit integers. See the wrapper functions below to correct for this problem.
Chr Returns a character given a character code. Returns a Variant/String.
Chr$ Returns a character given a character code. Returns a String.
ChrB Returns a single-byte string representing a character given a character code. Returns a Variant/String. *Try StrConv(ChrB(65),vbUnicode)
ChrB$ Returns a single-byte string representing a character given a character code. Returns a String. *Try StrConv(ChrB$(65),vbUnicode).
ChrW Returns a character given a Unicode character code if Unicode is supported. If Unicode is not supported it is the same as Chr. Returns Variant/String. *Do not use ChrW on a Mac.
ChrW$ Returns a character given a Unicode character code if Unicode is supported. If Unicode is not supported it is the same as Chr$. Returns String. *Do not use ChrW$ on a Mac.
Filter Returns an array containing a filtered subset of a string array.
Format Returns a string formatted by a given a format expression. Returns Variant/String.
Format$ Returns a string formatted by a given a format expression. Returns String.
FormatCurrency Returns a string formatted as a currency. Uses the currency symbol defined in the system control panel.
FormatDateTime Returns a string formatted as a date or time.
FormatNumber Returns a string formatted as a number.
FormatPercent Returns a string formatted as a percentage.
InStr Returns the position of the first occurrence of one string within another string.
InStrB Returns the byte position of the first occurrence of one string within another string.
InStrRev Returns the position of an occurrence of one string within another string starting from the end of the string and searching toward the start of the string.
Join Returns a string containing the elements of an array joined together by a delimiter.
LCase Returns a string converted to lowercase. Returns Variant/String.
LCase$ Returns a string converted to lowercase. Returns String.
Left Returns a substring of a given length from the left side of a string. Returns Variant/String.
Left$ Returns a substring of a given length from the left side of a string. Returns String.
LeftB Returns a substring of a given length in bytes from the left side of a string. Returns Variant/String.
LeftB$ Returns a substring of a given length in bytes from the left side of a string. Returns String.
Len Returns the number of characters in a string or the number of bytes required to store a variable.
LenB Returns the number of bytes in a string or the number of bytes required to store a variable.
LTrim Returns a string without leading spaces. Returns Variant/String.
LTrim$ Returns a string without leading spaces. Returns String.
Mid Returns a substring of a given length. Returns Variant/String. Can be used to alter sections of a string.
Mid$ Returns a substring of a given length. Returns String. Can be used to alter sections of a string.
MidB Returns a substring of a given length in bytes. Returns Variant/String. Can be used to alter sections of a string.
MidB$ Returns a substring of a given length in bytes. Returns String. Can be used to alter sections of a string.
MonthName Returns a string representing a given month.
Replace Returns a string with a given substring replaced by another string. Returns String.
Right Returns a substring of a given length from the right side of a string. Returns Variant/String.
Right$ Returns a substring of a given length from the right side of a string. Returns String.
RightB Returns a substring of a given length in bytes from the right side of a string. Returns Variant/String.
RightB$ Returns a substring of a given length in bytes from the right side of a string. Returns String.
RTrim Returns a string without trailing spaces. Returns Variant/String.
RTrim$ Returns a string without trailing spaces. Returns String.
Space Returns a given number of spaces. Returns Variant/String.
Space$ Returns a given number of spaces. Returns String.
Split Returns a string array by splitting up a string on a delimiter.
StrComp Returns the result of a string comparison.
StrConv Returns a string converted according to a given option.
String Returns a string repeated for a given number of times. Returns Variant/String.
String$ Returns a string repeated for a given number of times. Returns String.
StrReverse Returns a reversed string.
Trim Returns a string without leading or trailing spaces. Returns Variant/String.
Trim$ Returns a string without leading or trailing spaces. Returns String.
UCase Returns a string converted to uppercase. Returns Variant/String.
UCase$ Returns a string converted to uppercase. Returns String.
WeekdayName Returns a string representing a given day of the week.
Public Function AscW2(Char As String) As Long

    'This function should be used instead of AscW

    AscW2 = AscW(Char)

    If AscW2 < 0 Then
        AscW2 = AscW2 + 65536
    End If

End Function

Public Function AscW2(Char As String) As Long

    'This function should be used instead of AscW

    AscW2 = AscW(Char) And &HFFFF&

End Function

Types of String Functions

The behaviors of several string functions in VBA can be altered by affixing a $, B, W, or some combination of the three to the end of the function name.

$ Functions

$ String functions explicitly return a String instead of a Variant/String. The String type uses less memory than the Variant/String type.

B Functions

B (Byte) String functions deal with bytes instead of characters.

W Functions

W (Wide) functions are expanded to include Unicode characters if the system supports Unicode.

String Classes

Using custom string classes can facilitate working with strings and make working with strings more efficient. the StringBuilder and ArrayList classes have high-level functionality and are designed to mitigate the inefficiencies of with working with strings.

StringBuilder

The StringBuilder class represents a single string that can be manipulated and mutated. The StringBuilder class improves efficiency by avoiding frequent reallocation of memory. The StringBuilder class has a number of high-level properties and methods that facilitate working with strings. Download and import the clsStringBuilder class into a VBA project.

Public Sub Example()

    '''Must import clsStringBuilder to VBA project

    Dim SB As clsStringBuilder
    Set SB = New clsStringBuilder

    SB.Append "ABC"
    SB.Append "123"

    SB.Insert 3, "XYZ"

    Debug.Print SB.Substring(3, 5)

    SB.Remove 3, 5

    Debug.Print SB.ToString

End Sub

ArrayList

The ArrayList class represents a list which can be manipulated and mutated. The ArrayList class improves efficiency by avoiding frequent reallocation of memory. The ArrayList class has a number of high-level properties and methods that facilitate working with a list of strings. Download and import the clsArrayListString class into a VBA project.

Public Sub Example()

    '''Must import clsArrayListString to VBA project

    Dim AL As clsArrayListString
    Set AL = New clsArrayListString

    'Build message
    AL.Append "Hello"
    AL.Append "How are you?"
    AL.Append "I'm great! Thank you."
    Debug.Print AL.JoinString(vbNewLine)

    AL.Reinitialize

    'Sort strings
    AL.Append "C"
    AL.Append "B"
    AL.Append "A"
    Debug.Print AL.JoinString
    AL.Sort
    Debug.Print AL.JoinString

End Sub

Понравилась статья? Поделить с друзьями:
  • Excel vba picture load
  • Excel vba listbox снять выделение
  • Excel vba for print
  • Excel vba personal xlsb
  • Excel vba listbox значение