Excel vba list of strings

In VBA, a String Array is nothing but an array variable that can hold more than one string value with a single variable.

For example, look at the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.

Table of contents
  • Excel VBA String Array
    • Examples of String Array in Excel VBA
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • Recommended Articles

Code:

Sub String_Array_Example()

Dim CityList(1 To 5) As Variant

CityList(1) = "Bangalore"
CityList(2) = "Mumbai"
CityList(3) = "Kolkata"
CityList(4) = "Hyderabad"
CityList(5) = "Orissa"

MsgBox CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4) & ", " & CityList(5)

End Sub

In the above code, we have declared an array variable and assigned the length of an array as 1 to 5.

Dim CityList(1 To 5) As Variant

Next, we have written a code to show these city names in the message box.

CityList(1) = "Bangalore"

CityList(2) = "Mumbai"

CityList(3) = "Kolkata"

CityList(4) = "Hyderabad"

CityList(5) = "Orissa"

Next, we have written a code to show these city names in the message box.

MsgBox CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4) & ", " & CityList(5)

When we run this code, we will get a message box that shows all the city names in a single message box.

VBA String Array Example 1-1

We all know this has saved much time from our schedule by eliminating the task of declaring individual variables for each city. However, one more thing you need to learn is we can still reduce the code of lines we write for string values. So, let’s look at how we write code for VBA stringString functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions.read more arrays.

Examples of String Array in Excel VBA

Below are examples of an Excel VBA string array.

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

Example #1

As we have seen in the above code, we learned we could store more than one value in the variable based on the array size.

We do not need to decide the array length well in advance.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

End Sub

VBA String Array Example 1-1

As you can see above, we have not written any lengths in the parenthesis. So now, for this variable, let’s insert values using VBA ARRAY functionArrays are used in VBA to define groups of objects. There are nine different array functions in VBA: ARRAY, ERASE, FILTER, ISARRAY, JOIN, LBOUND, REDIM, SPLIT, and UBOUND.read more.

VBA String Array Example 1-2.png

Inside the array, pass the values on double quotes, each separated by a comma (,).

Code:

Sub String_Array_Example()

Dim CityList() As Variant

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

End Sub

VBA String Array Example 1-3.png

Now, retain the old code to show the result of city names in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

MsgBox CityList(0) & ", " & CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4)

End Sub

One change we have made in the above code is that we have not decided on the lower limit and upper limit of an array variable. Therefore, the ARRAY function array count will start from 0, not 1.

So, that is the reason we have mentioned the values as  CityList(0), ClityList(1), CityList(2), CityList(3), and CityList(4).

Now, run the code through excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5 or manually. Again, we get the same result as the previous code.

VBA String Array Example 1.gif

Example #2

VBA String Array with LBOUND & UBOUND Functions

If you don’t want to show all the city lists in a single message box, then you need to include loops and define one more variable for loops.

VBA String Array Example 1-6

Now, to include FOR NEXT loop, we are unsure how many times we need to run the code. Of course, we can decide five times in this case, but that is not the right way to approach the problem. So, how about the idea of auto lower and higher level array length identifiers?

When we open FOR NEXT loop, we usually decide the loop length as 1 to 5 or 1 to 10, depending upon the situation. So, instead of manually entering the numbers, let’s automatically use the LBOUND and UBOUND functions to decide on the lower and upper values.

VBA String Array Example 1-7

For LBound and Ubound, we have supplied an array name, CityList. The VBA LBoundLBound in VBA or “Lower Bound” extracts the lowest number of an array. For example, if the array says “Dim ArrayCount (2 to 10) as String” then using LBound function we can find the least number of the array length i.e. 2.read more identifies the array variable’s lower value. The VBA UBound functionUBOUND, also known as Upper Bound, is a VBA function that is used in conjunction with its opposite function, LBOUND, also known as Lower Bound. This function is used to determine the length of an array in a code, and as the name suggests, UBOUND is used to define the array’s upper limit.read more identifies the upper value of the array variable.

Now, show the value in the message box. Instead of inserting the serial number, let the loop variable “k” take the array value automatically.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

Dim k As Integer

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

For k = LBound(CityList) To UBound(CityList)

MsgBox CityList(k)

Next k

End Sub

LBound & UBound Example 1-8

Now, the message box will show each city name separately.

VBA String Array Example 1.gif

Example #3

VBA String Array with Split Function

Now, assume you have city names like the one below.

Bangalore;Mumbai;Kolkata;Hydrabad;Orissa

In this case, all the cities combine with the colon separating each city. Therefore, we need to use the SPLIT function to separate each city in such cases.

Split Example 2

For Expression, supply the city list.

Code:

Sub String_Array_Example2()

Dim CityList() As String

Dim k As Integer

CityList = Split("Bangalore;Mumbai;Kolkata;Hydrabad;Orissa",

For k = LBound(CityList) To UBound(CityList)
MsgBox CityList(k)
Next k

End Sub

Split Example 2-1

The next argument is “Delimiter,” which is the one character separating each city from other cities. In this case, “Colon.”

Code:

Sub String_Array_Example2()

Dim CityList() As String

Dim k As Integer

CityList = Split("Bangalore;Mumbai;Kolkata;Hydrabad;Orissa", ";")

For k = LBound(CityList) To UBound(CityList)
MsgBox CityList(k)
Next k

End Sub

split Example 2-2.png

Now, the SPLIT function split values determine the highest array length.

Things to Remember

  • The LBOUND and UBOUND are functions to determine the array lengths.
  • The ARRAY function can hold many values for a declared variable.
  • Once we want to use the ARRAY function, do not decide the array length.

Recommended Articles

This article is a guide to VBA String Array. Here, we discuss how to declare the VBA string array variable, which can hold more than one string value, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA String Comparison
  • Find Array Size in VBA
  • SubString in Excel VBA
  • Variant Data Type in VBA

Содержание

  1. VBA Declare & Initilize String Array
  2. Declaring a String variable
  3. Declaring a Static String Array
  4. Declaring a Variant Array using the Array function
  5. Declaring a String Array using the Split Function
  6. VBA Coding Made Easy
  7. VBA Code Examples Add-in
  8. VBA String Functions
  9. Excel VBA String Functions
  10. List of Top 6 String Functions in VBA
  11. #1 – LEN Function
  12. #2 – LEFT Function
  13. #3 – RIGHT Function
  14. #4 – MID Function
  15. #5 – TRIM Function
  16. #6 – Instr Function
  17. Recommended Articles
  18. Declare VBA Array of Strings using Split
  19. The VBA Tutorials Blog
  20. Introduction — VBA Array of Strings
  21. Example — VBA Array of Strings
  22. Tutorial — VBA Array of Strings
  23. Items to Consider — VBA Array of Strings
  24. Delimiters
  25. Spaces
  26. Application Ideas — VBA Array of Strings
  27. Bonus Macro — Array of Months
  28. VBA String Functions and how to use them
  29. The VBA Tutorials Blog
  30. VBA String Functions
  31. VBA Concatenation in Two Flavors
  32. The VBA Join Function
  33. Separating Strings with Split
  34. Adding and Removing Spaces
  35. The Space function
  36. Removing Spaces
  37. Numbers in Strings
  38. Consistency in Comparisons (and Aesthetics)
  39. Extracting Substrings
  40. Using Space to Standardize Data
  41. Conclusion

VBA Declare & Initilize String Array

In this Article

This tutorial will teach you how to declare and initialize a string array in VBA.

Declaring a String variable

When you declare a string variable in VBA, you populate it by adding a single string to the variable which you can then use in your VBA code.

Declaring a Static String Array

If you want to populate an array with a string of values, you can create a STATIC string array to do so.

Remember that the Index of an Array begins at zero – so we declare the Array size to be 2 – which then enables the Array to hold 3 values.

Instead, you can explicitly define the start and end positions of an array:

Declaring a Variant Array using the Array function

If you want to populate an array with a string of values without implicitly stating the size of the Array, you can create a variant array and populate it using the Array function.

Declaring a String Array using the Split Function

If you want to keep the variable as a string but do not want to implicitly state the size of the Array, you would need to use the Split function to populate the array.

The Split function allows you to keep the data type (eg String) while splitting the data into the individual values.

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!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA String Functions

Excel VBA String Functions

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.

Table of contents

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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA String Functions (wallstreetmojo.com)

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

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

#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 excel LEN In Excel The 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:

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

#2 – LEFT Function

  • 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:

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

#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 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:

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

#4 – MID Function

  • 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:

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

#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.

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:

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

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:

  • [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:

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

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

Code:

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

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: –

Источник

Declare VBA Array of Strings using Split

The VBA Tutorials Blog

Introduction — VBA Array of Strings

This tutorial shows you how to declare and initialize a VBA array of strings using the Split function. This array of strings solution is compact and efficient, saving memory and reducing VBA execution time

Example — VBA Array of Strings

Make powerful macros with our free VBA Developer Kit

This is actually pretty neat. If you have trouble understanding or remembering it, our free VBA Developer Kit can help. It’s loaded with VBA shortcuts to help you make your own macros like this one — we’ll send a copy, along with our Big Book of Excel VBA Macros, to your email address below.

Tutorial — VBA Array of Strings

The example macro uses the VBA Split function to create an array with 3 elements, numbered from 0 to 2. It’s a compact, one-line solution to making arrays of strings with VBA. Let’s explain how it works.

The Split function takes a string (your first argument) and splits it into an array at the delimiter you give in the second argument. In the example macro, I split my string at each comma.

The beauty of this approach is you don’t have to know how big your array is before creating it! Notice, I didn’t define the size of my string array with my Dim statement. The Split function just knows how big it needs my new array to be.

The result is an array of strings with 3 elements, defined below:

In this tutorial, we showed you how to quickly declare an array of strings by taking advantage of how the VBA Split function behaves. That’s just one many tricks included in our comprehensive VBA Arrays Cheat Sheet which has over 20 pre-built macros and dozens of tips designed to make it easy for you to handle arrays.

Items to Consider — VBA Array of Strings

Delimiters

It’s important to recognize when your list of strings might actually contain a comma. If you find yourself in this situation, simply enter a new delimiter, like a semi-colon:

Spaces

Notice how I don’t have spaces immediately before or after my delimiter — the comma, or semi-colon in the above examples. If you put a space, the space will be retained as part of your split string. In other words, you may have a leading or a trailing space before or after your string in the array.

Application Ideas — VBA Array of Strings

Arrays of strings are useful. Many people find themselves needing to create an array of months in Excel VBA. You can do this in a number of ways, but since we’re talking about the Split method, that’s what I’m going to show. It’s almost Christmas, so I’m giving this gift for you to use in whatever project you’re working on!

Bonus Macro — Array of Months

When you’re done with this tutorial, I hope you’ll read my tutorials on other string manipulation functions.

Please, share this article on Twitter and Facebook. Sharing on social media is how I’m able to reach and teach more people about the awesome power of VBA.

I want to thank all my readers who have already subscribed to my free wellsrPRO VBA Training Program and I encourage you to go ahead and subscribe using the form below if you haven’t done so. You’ll love the great VBA content I send your way!

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

VBA String Functions and how to use them

The VBA Tutorials Blog

This tutorial describes VBA string functions, explains how to use basic VBA string functions in your own macros, and guides you to detailed tutorials covering advanced VBA string functions. It’s everything you need to know about working with strings in VBA, all in one place.

One of the most basic types of data structures is the string. A VBA string is just like a string in any other programming language; it’s a character or a series of characters set next to each other in a particular order. Unlike some other data structures, like VBA dictionaries, the order is important. Clearly the strings, “hello world” and “dello whorl” are, and should be, treated differently.

VBA offers several ways to manipulate these basic data structures. We’ll describe the main VBA string functions in this tutorial. You can create some really advanced VBA string functions using things like VBA RegEx, which can add significant firepower to your string-manipulation toolbox.

VBA String Functions

Here’ a list of the most commonly used VBA string functions and a description of what they do. This is an incredibly helpful table, so I encourage you to refer to it any time you’re working with strings in your VBA macros. The table will link you to detailed tutorials about some of the string functions so you can read more about how to use them.

String Function Type of Operation Description
& Concatenation Combines the strings on either side
+ Concatenation Concatenates (combines) the strings on either side, if and only if they are both strings. If you try to concatenate a string holding a number and a number (integer, double, etc), the + operator will add your numbers instead of concatenating them.
Join Concatenation Joins the strings in the input array, optionally delimited by a string of your choice (strings can be punctuation)
Split Reverse Concatenation Splits up the input string into an array. Splits based on the chosen delimiter and each item in your string becomes its own element in the array.
LTrim, RTrim, Trim Space Removal Removes all leading, trailing, or leading and trailing spaces from a string
Space Space Addition Creates a string with the specified number of spaces
Replace Substitution Substitutes some string for another string. Often used for removing spaces or systematically changing strings
Val Type Conversion Converts a string into a decimal number
CInt Type Conversion Converts a string into an integer using banker’s rounding, if necessary
CStr Type Conversion Converts a number to a string
CDate Type Conversion Converts a string to a date, so you can use date arithmetic and apply date functions.
StrComp Comparison Compare two input strings, can be case sensitive or insensitive
LCase, UCase Case Conversion Converts a string to all lower or upper case, which can be useful when comparing VBA strings
StrConv Case Conversion Another way to convert ASCII strings to upper case, lower case, or proper case (first letter of each word capitalized). The StrConv function also lets you convert from ASCII to Unicode and back.
Left, Right String Extraction Returns the substring of a given length. The length is counted from the beginning or end, depending on whether you’re using the Left or Right function.
Mid String Extraction Returns the string of optional given length, starting at the given position. Always counts from the beginning.
InStr String Extraction Returns the starting position (index starting at 1) of the specified string within another string, or 0 if the substring is not found in the main string.
InStrRev String Extraction Returns the starting position of the specified substring, but starts counting from the end of your string.

Make powerful macros with our free VBA Developer Kit

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

VBA Concatenation in Two Flavors

You can concatenate VBA strings in two ways: via the ampersand/plus and via the Join function. The first requires you to add an ampersand (&) or a plus sign (+) between every string. For short sets, (one or two small strings), this isn’t so difficult.

Warning: The plus sign does NOT behave the same way as the ampersand. The ampersand should almost always be used. Take a look at my full VBA Concatenation tutorial to understand what I mean.

Our output? Hello World.Hello Friend.

The first thing you may notice is there is no space. For that, you can add your own space using, like this:

Now we get Hello World. Hello Friend. .

Now imagine you have 50 strings. You can imagine how tedious this would be, since you’d have to type a lot of » » and & in your macros. Yes, you could use a for-loop to go through each iteration and build the string that way, but there is a better method.

The VBA Join Function

The Join function is the first of several VBA string functions we’ll discuss. If you happen to have all your strings in an array already, which very well might be the case if you read several strings from a sheet into an array, you can concatenate them and even add a delimiter between them using the VBA Join function.

By specifying the space in the optional [Delimiter] argument, you’ll automatically separate every string with that delimiter. You could even do it with other strings, like so:

Which will yield us Hello World. 🙂 Hello Friend. 🙂 Hello All.

Separating Strings with Split

Now let’s say you want to extract the sentences from your longer string “Hello World. Hello Friend.” One way to do it is to use our second VBA string function: the Split function. Take a look at the macro example:

Now, the array string_arr holds three items:

The first two make sense, but what happened with the third? Well, Split found the last period and wrote whatever came after the period as another string. It just happened to be empty.

You can use VBA UBound to check if the last item is empty, and if it is, just reference the preceding inputs in the array:

Using last_item as your final index will ignore the empty string at the end.

You can see more about splitting in our full VBA Split tutorial.

Adding and Removing Spaces

Sometimes we need to work with padded strings. Padded strings are strings with extra spaces embedded within them, like at the beginning or end. The function to add spaces to a string is Space . Similarly, there are three functions designed to remove spaces from a string: LTrim , RTrim , and Trim (as they “trim” the spaces off the string).

The Space function

To add a number of spaces, you can simply write my_padded_string = Space([num]) where [num] is the number of spaces.

Why would you want to do this? Well, it is one way to add the delimiter in the Join function:

It can also be useful for placeholders when data is not available yet, but you know exactly how long the string will be. Sometimes programs require a minimum length of string before they execute. Space can help you circumvent that requirement until you have data to fill up the string.

It is also useful if other code is position-based and you need to always have 10 characters, for example, before another part. We’ll talk more about that in the Substring section, but it’s very common to have to process or generate fixed width data. Creating algorithms with the VBA space function is perfect for that.

Removing Spaces

You can use the various trim functions to remove spaces. We’ve talked about how to use the VBA RTrim function, in combination with other functions, to remove whitespace characters other than simple spaces.

The trim functions are especially useful if you have user-entered data. Often users will add extra spaces for whatever reason. Whatever their reason, you might need to remove these extra spaces from a string.

LTrim removes spaces from the left
RTrim removes spaces from the right
Trim removes spaces from both sides

You can also use the VBA Replace function to remove spaces. As a matter of fact, you can use the VBA Replace function to replace any substring with a new substring.

Numbers in Strings

Ah, the deceptive number as a string. If you are not careful, these kinds of hidden issues will throw all kinds of mismatch errors your way. We warned you about this when talking about concatenating strings!

If you have just the number in a cell, there’s a good chance it’s formatted as text. If it is formatted as text, you ought to convert it before using it for math operations.

Usually we want to use integers (especially if you’ll be using it in a for-loop) or floating point numbers (i.e., decimal values).

The program below will not output 30.84 :

Instead, we get 10.520.34 as my_num3, which is not actually a decimal number. Why is that? Well, VBA is treating these as strings!

This is why you need to convert your strings to numbers. If you don’t, VBA might not know you want to use them as numbers. To VBA, they look exactly like strings. Likewise, there are instances where VBA will try to convert your strings to numbers for you, whether you want it to or not. This is exactly why you ought to be explicit when converting your strings.

Now we get the desired 30.84 result.

If you don’t want to deal with decimals, you can always round up/down by using the CInt function:

Now we get 30 . Note, you wouldn’t be able to write your function like CInt(my_num + my_num2) , since the “numbers” would still be treated as strings during the “addition” concatenation part. We have a thorough VBA CInt tutorial if you want to read more about converting strings (and other data types) to integers.

To reverse the conversion (i.e., number to string), check out our VBA CStr tutorial. The CStr function is exactly what you want to use to convert a number to a string for use in your string manipulation routines.

Consistency in Comparisons (and Aesthetics)

One of the most useful things a computer can do is compare large amounts of data very quickly. Computers revel in such tedium, and they have very strong skills in the area.

Foreword: If you want to compare strings without this step, you can do so by using the VBA StrComp function.

You can easily compare strings in if-statements like this:

Unfortunately, this will never trigger the MsgBox. Why not? Because these strings aren’t actually the same. We can make them the same with UCase or LCase .

To ensure consistency in your comparison functions, it is good to either use the StrComp function with case insensitivity or convert all strings to the same case, like we did in our compare cells using VBA tutorial.

Ensuring letter case consistency is as simple as this:

You could implement LCase instead of UCase if you prefer.

Sometimes we really don’t care about the whole string. We just want to focus on a part of it. If you have tidy, pre-formatted and cleansed data, you can use the Left , Right , or Mid functions to do the extraction.

These functions take a string as an input and output a string of a specified length. This is paricularly useful if you have strings that always start with, say, a timestamp.

This is some (fictitious) trade information for Bitcoin on May 20, 2018 at 8:23:15 AM UTC.

Since dates will always be in this format, you can always use the Left function to easily extract the date. Extracting any other information (the price, the volume) is not easily done with these substring functions, since their positions can move. You have a couple better options. One thing you could do use use the VBA Split function we discussed earlier to split the string at each space. Another way to do it is to use the VBA InStr function to find the tag (BTC, USD, BTCVOL) and chop the string up into pieces based on positions and lengths.

If you really wanted to use Left , Right , and InStr , you could do it this way:

Of course, this only works if the structure of the string doesn’t change. If your API starts outputting date-vol-price formats, you’ll be capturing the vol and the price, not just the price. Hence leveraging VBA Regular Expressions is much better in this situation.

We didn’t use it in our examples, but the VBA Mid function is particularly useful. We’ve even developed a user-defined function to make extracting substrings even easier.

Using Space to Standardize Data

One reason to use the Space function is to standardize your data. If you are generating the data yourself, you might have a tool to capture names and jobs, like this:

Then you might have some function to extract the job, like this. This is a silly example, I know, but stick with me.

Unfortunately, unless your user’s name is exactly 37 characters, you’re going to end up with something that is not a job. (That is 37 characters for the name plus 6 for “ Job: “, plus 6 for “Name: “, and finally plus one more to start after the space in “Job: “).

The easiest way to make this function work properly is to implement the Space function to pad everything first.

Now your string for the job will always start at 50, and your function will work fine. When reading back these values, remember to use the trim functions to get cleaner results.

Conclusion

These are some of the main string functions with examples and links for how to use them. If you want some more details, you can see the list of string articles on this page. We’ve already written about other common ones, like Replace, InStrRev, and StrConv.

String manipulation is one of the most basic computer science operations, and their natural representations in computing makes them easy to manipulate. Understanding the functions that are associated with them is an excellent way to build a solid foundation in VBA.

That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

This article was written by Cory Sarver, a contributing writer for The VBA Tutorials Blog. Visit him on LinkedIn and his personal page.

Источник

Return to VBA Code Examples

In this Article

  • Declaring a String variable
  • Declaring a Static String Array
  • Declaring a Variant Array using the Array function
  • Declaring a String Array using the Split Function

This tutorial will teach you how to declare and initialize a string array in VBA.

Declaring a String variable

When you declare a string variable in VBA, you populate it by adding a single string to the variable which you can then use in your VBA code.

Dim strName as String
StrName = "Bob Smith"

Declaring a Static String Array

If you want to populate an array with a string of values, you can create a STATIC string array to do so.

Dim StrName(2) as String 
StrName(0) = "Bob Smith"
StrName(1) = "Tom Jones"
StrName(2) = "Mel Jenkins"

Remember that the Index of an Array begins at zero – so we declare the Array size to be 2 – which then enables the Array to hold 3 values.

Instead, you can explicitly define the start and end positions of an array:

Dim StrName(1 to 3) as String 
StrName(1) = "Bob Smith"
StrName(2) = "Tom Jones"
StrName(3) = "Mel Jenkins"

Declaring a Variant Array using the Array function

If you want to populate an array with a string of values without implicitly stating the size of the Array, you can create a variant array and populate it using the Array function.

Dim strName as Variant
strName = Array("Bob Smith", "Tom Jones", "Mel Jenkins")

Declaring a String Array using the Split Function

If you want to keep the variable as a string but do not want to implicitly state the size of the Array, you would need to use the Split function to populate the array.

Dim strName() as String 
strNames = Split("Bob Smith, Tom Jones, Mel Jenkins")

The Split function allows you to keep the data type (eg String) while splitting the data into the individual values.

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!
vba save as

Learn More!

VBA String Array

Excel VBA String Array

When we have multiple variables to be declared in a VBA Code, we can declare the exact number of a variable with data type we want. But this process is quite lengthy when the variable count goes above 5. Why declare variables multiple times when we can frame that into String Array. A VBA String Array is used when we need to hold more than one string value with a string variable. This looks tricky but in reality, it is very easy to implement. We don’t have to declare one type of variable multiple times if each variable store’s different values. This slash in a huge VBA Code is done using Excel VBA String Array.

How to Use VBA String Array?

To use VBA String Array in any code, it is very simple. For this, we just need to define how many variables we will require. This will be first done using DIM. Suppose, if we want 10 variables of any data type so that could be done as shown below.

Code:

Sub VBA_StringArray()

Dim NameOfVariable(1 To 10) As DataType

End Sub

VBA String Array Examples

We can choose any name in place Name Of Variable and any data type in Data Type box as highlighted above.

Examples of String Array in Excel VBA

Below are the examples of an excel VBA string array.

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

Example #1

In this example, we will see how to use String Array in VBA without any limit in variables. Here, we will not define the length of variables, instead, we will directly create string array and use the number of variables as we our need. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Define the subprocedure preferably in the name of VBA String Array or we can choose any name as per our choice.

Code:

Sub VBA_StringArray1()

End Sub

VBA String Array Examples 1-1

Step 3: Now we will be using Employee names for creating the array. For this declare a variable in a similar name and put brackets “( )” after that. And choose any data type. We can choose String or Integer or Variant. But as the data may vary so using Variant will be good.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant

End Sub

Variant Examples 1-2

Step 4: Now use the same variable which we declared above and use Array function.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array(

End Sub

VBA String Array Examples 1-3

As we can see, as per the syntax of Array, it only allows Variant data type and Argument List (). The reason for seeing the Variant data type is because we can store any type of value in it.

Step 5: Now consider the names of employees which we will be using here. We have Anand, Shraddha, Aniket, Ashwani, and Deepinder as Employee names. And it should be in the way as we do concatenation.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array("Anand", "Shraddha", "Aniket", "Ashwani", "Deepinder")

End Sub

Employee names Examples 1-4

Step 6: And to print the values stored in the Employee Data array we will use MsgBox. And array will be in the sequence of numbers at which we have defined.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array("Anand", "Shraddha", "Aniket", "Ashwani", "Deepinder")
MsgBox EmployeeData(0) & ", " & EmployeeData(1) & ", " & EmployeeData(3) & ", " & EmployeeData(4)

End Sub

VBA String Array Examples 1-6

Step 7: Run this code by hitting the F5 or Run button which is placed on the topmost ribbon of VBE.

Run button Example

Step 8: We will get the message box with all the employee names in the sequence we put it.

VBA String Array Examples 1-8

Step 9: Let’s try to change the sequence of Employee Data array. Here we have exchanged 0 and 4 with each other.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array("Anand", "Shraddha", "Aniket", "Ashwani", "Deepinder")
MsgBox EmployeeData(4) & ", " & EmployeeData(1) & ", " & EmployeeData(3) & ", " & EmployeeData(0)

End Sub

Employee names Examples 1-9

Step 10: Let’s run this code again. We will notice, Employee Data name Deepinder is now moved to first place and Anand is at 4th place.

VBA String Array Examples 1-6

Example #2

In this example, we will set the position of cells in the array and get the combination of output by that. For this, we will use the same employee names which we have seen in. For this, follow the below steps:

Step 1: Write the subprocedure.

Code:

Sub VBA_StringEmployeDataay2()

End Sub

VBA String Array Examples 2-1

Step 2: Define a variable as Variant with cell positioning as (1, 3) Which 1 shows the 2nd position.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant

End Sub

VBA String Array Examples 2-2

Step 3: Now we will assign each employee name to different co-ordinates. Such as, at 1st row, 2nd column we have set employee Anand.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"

End Sub

VBA String Array Examples 2-3

Step 4: Similarly we will choose different co-ordinates from (1, 3) position and give each employee name in a different position.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"

End Sub

VBA String Array Examples 2-4

Now to get the output from the defined array, we will use the message box.

Step 5: We have used the position of co-ordinates. Such as for (0, 1).

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"
MsgBox ("EmployeData In Index 0,1 : " & EmployeData(0, 1))

End Sub

VBA String Array Examples 2-5

Step 6: Similarly, another message box to see other values stored in different co-ordinates.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"
MsgBox ("EmployeData In Index 0,1 : " & EmployeData(0, 1))
MsgBox ("EmployeData In Index 1,2 : " & EmployeData(1, 2))

End Sub

VBA String Array Examples 2-6

Step 7: Once done, compile the code by hitting the F8 or Run button. We will see, the values stored in the array (0, 1) is Anand.

Message Box Examples 2-7

Step 8: And the second array (1, 2) stores the value as Aniket.

Message Box Examples 2-8

This is how co-ordinating in String array works.

Step 9: What if we change the array co-ordinates for the second message box from (1, 2) to (2, 2).

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"
MsgBox ("EmployeData In Index 0,1 : " & EmployeData(0, 1))
MsgBox ("EmployeData In Index 1,2 : " & EmployeData(2, 2))

End Sub

VBA String Array Examples 2-9

Step 10: We will see, once the first array message box shows the value, the second message box will give the error, as Subscript Out Of range. Which means, we have selected the range which either incorrect or not exists.

VBA String Array Examples 2-10

Pros of VBA String Array:

  • VBA String Array can hold any type of value.
  • There is no limit to storage capacity in String Array.

Things to Remember

  • We can create 2D and 3D String array both.
  • Called value of array should be in the range of defined values.
  • It is not advised to fix the length of the array. Because if the value of an array is out of range, then we will end up getting the error.
  • Also, save the file in macro enable excel format to preserve the written VBA Code.
  • We can use different functions such as LBOUND, UBOUND, Split, Join, Filter, etc. in String Arrays using Loops.

Recommended Articles

This is a guide to the VBA String Array. Here we discuss how to use String Array in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA SendKeys
  2. VBA Name Worksheet
  3. VBA CInt
  4. VBA SubString

Home / VBA / Arrays / VBA Array with Strings

In VBA, you can create an array with strings where each element of the array stores one string that you can further access or even combine into one string. Apart from this, you can also split the main string into multiple sub-strings (using a delimiter) and then store each of them into the array’s elements.

As I said above, there are two ways to use strings in an array, and in this tutorial, we will see how to write code for both.

Option Base 1
Sub vba_string_array()

Dim myArray() As Variant
myArray = Array("One", "Two", "Three")
   
Debug.Print myArray(1)
Debug.Print myArray(2)
Debug.Print myArray(3)
      
End Sub
  1. First, declare an array without the element count that you want to store in there.
  2. Next, you need to use VBA’s ARRAY function to define the value that you want to specify.
  3. After that, specify all the strings using a comma into the function.
  4. In the end, you can access all the strings using the element number.

In the same way, you can also get a string from the cells to store in the array.

VBA Split String and Store in an Array

If you want a string that has multiple substrings you can split it using the VBA’s SPLIT function which uses a delimiter.

Option Base 1
Sub vba_string_array()

Dim myArray() As String
myArray = Split("Today is a good day", " ")
For i = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(i)
Next i
      
End Sub

In this code, you have a string which is a sentence that has five words. And when you use the split function it splits it into five different substrings, and then you have stored it in the elements of the array.

After that, you have the for loop which uses the upper and lower bound for the counter to loop and prints each element of the array into the immediate window.

Понравилась статья? Поделить с друзьями:
  • Excel vba for end for
  • Excel vba line input
  • Excel vba like and not like
  • Excel vba for each row in range
  • Excel vba left описание