Matriz de cadenas VBA - ¿Cómo declarar e inicializar una matriz de cadenas en Excel VBA?

Tabla de contenido

Matriz de cadenas de Excel VBA

En VBA, una matriz de cadenas no es más que una variable de matriz que puede contener más de un valor de cadena con una sola variable.

Por ejemplo, mire el siguiente código VBA.

Código:

Sub String_Array_Example () Dim CityList (1 a 5) Como variante 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

En el código anterior, he declarado como variable de matriz y he asignado la longitud de una matriz de 1 a 5.

Dim CityList (1 a 5) como variante

Para esta variable de matriz, he asignado 5 nombres de ciudades que mencionan cada recuento de matriz entre paréntesis.

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

A continuación, escribí un código para mostrar estos nombres de ciudades en el cuadro de mensaje.

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

Cuando ejecuto este código, obtendremos un cuadro de mensaje que muestra todos los nombres de las ciudades en un solo cuadro de mensaje.

Todos sabemos que esto nos ha ahorrado mucho tiempo de nuestro programa al eliminar la tarea de declarar variables individuales para cada ciudad. Sin embargo, una cosa más que debe aprender es que aún podemos reducir el código de línea que escribimos para valores de cadena. Veamos cómo escribimos código para matrices de cadenas VBA.

Ejemplos de matriz de cadenas en Excel VBA

A continuación se muestran los ejemplos de una matriz de cadenas de Excel VBA.

Ejemplo 1

Como hemos visto en el código anterior, aprendimos que podíamos almacenar más de un valor en la variable en función del tamaño de matriz determinado.

Ahora lo que tenemos que hacer es no decidir la longitud de la matriz con mucha anticipación.

Código:

Sub String_Array_Example1 () Dim CityList () como variante End Sub

Como puede ver arriba dentro del paréntesis, no he escrito ninguna extensión. Ahora para esta variable, insertemos valores usando la función VBA ARRAY.

Dentro de la matriz, pase los valores entre comillas dobles, cada una separada por una coma (,).

Código:

Sub String_Array_Example () Dim CityList () Como variante CityList = Array ("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa") End Sub

Ahora conserve el código anterior para mostrar el resultado de los nombres de las ciudades en el cuadro de mensaje en VBA.

Código:

Sub String_Array_Example1 () Dim CityList () como variante CityList = Array ("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa") MsgBox CityList (0) & "," & CityList (1) & " , "& CityList (2) &", "& CityList (3) &", "& CityList (4) End Sub

Un cambio que hice en el código anterior es que no hemos decidido el límite inferior y el límite superior de una variable de matriz, y hemos utilizado la función ARRAY. El recuento de matrices comenzará desde 0, no desde 1.

Entonces, esa es la razón por la que hemos mencionado los valores como CityList (0), ClityList (1), CityList (2), CityList (3) y CityList (4).

Ahora ejecute el código a través de la tecla de método abreviado de Excel F5 o manualmente. Obtenemos el mismo resultado que obtenemos del código anterior.

Ejemplo # 2

VBA String Array with LBOUND & UBOUND Functions

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

Now to include FOR NEXT loop, we are not sure how many times we need to run the code. In this case, we can decide it like 5 times, but that is not the right way to approach the problem. So how about the idea of auto lower and higher level array length identifier???

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

For LBound and Ubound, I have supplied an array name, i.e., CityList. VBA LBound identifies the lower value of the array variable, and VBA UBound function 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” takes 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

Now the message box will show each city name separately.

Example #3

VBA String Array with Split Function

Now assume you have city names like the below.

Bangalore;Mumbai;Kolkata;Hydrabad;Orissa

In this case, all the cities are combined together with the colon separating each city. In such cases, we need to use the SPLIT function to separate each city.

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

The next argument is “Delimiter,” i.e., what is the one character that is 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

Ahora, los valores divididos de la función SPLIT también determinan la longitud más alta de la matriz.

Cosas para recordar

  • LBOUND y UBOUND son funciones para determinar las longitudes de la matriz.
  • La función ARRAY puede contener muchos valores para una variable declarada.
  • Una vez, si desea utilizar la función ARRAY, no decida la longitud de la matriz.

Articulos interesantes...