Excel vba string not in array

  • #2

Filter works on partial matches, so «a» is in the final array in the form of «a-b». Your second to last example works correctly for me

  • #3

Filter works on partial matches, so «a» is in the final array in the form of «a-b». Your second to last example works correctly for me

If Filter works on partial matches then that is where I am going wrong. Can you (or anyone else) suggest an alternate method of checking whether an item is in an array?

Edit: yes you are write about my second last example. That actually does work correctly. I got that example the wrong way around. But I think people should be able to get my drift.

Last edited: Sep 2, 2013

  • #4

Perhaps more resilient, but not fool proof:

Code:

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = InStr(1, vbCr & Join(arr, vbCr) & vbCr, vbCr & stringToBeFound & vbCr)
End Function

Though it’s worth mentioning, that looping through arrays in memory is pretty fast, so shouldn’t be ruled out. These approaches also will only work on arrays with a single dimension — they fail in the case of a 2d array which are very common in Excel

  • #5

Hi Harry

Filter does not perform an exact match.

Another option:

Code:

  IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))

snb_

Well-known Member


  • #6

Code:

Sub M_snb()
    sn = Array("aa1", "aa2", "bb3")
    
    c00 = "aa1"
    c01 = "b"
    c02 = "Exact match: "
    
    MsgBox c02 & Format(InStr("~" & Join(sn, "~|~") & "~", "~" & c00 & "~"), "yes/no")
    MsgBox c02 & Format(InStr("~" & Join(sn, "~|~") & "~", "~" & c01 & "~"), "yes/no")

    MsgBox c02 & Format(UBound(Filter(Split("~" & Join(sn, "~|~") & "~", "|"), "~" & c00 & "~")) > -1, "yes/no")
    MsgBox c02 & Format(UBound(Filter(Split("~" & Join(sn, "~|~") & "~", "|"), "~" & c01 & "~")) > -1, "yes/no")

    MsgBox c02 & Format(Not IsError(Application.Match(c00, sn, 0)), "yes/no")
    MsgBox c02 & Format(Not IsError(Application.Match(c01, sn, 0)), "yes/no")
End Sub

  • #7

Hi Harry

Filter does not perform an exact match.

Another option:

Code:

  IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))

Thank you that was exactly what I was looking for.

This problem has a small piece of the jigsaw puzzle that I posted in this thread:
http://www.mrexcel.com/forum/excel-…-value-exists-new-collection.html#post3561227

Which was itself a small piece in a larger jigsaw puzzle.

My original question was how could I check if an item was in a New Collection, which I never figured out. So I thought I would try passing my New Collection to an array and find someway to check that.

Thanks to Kyle123 and snb_ as well for their input too. Much appreciated. I am teaching myself VBA from books and I no one at my work knows anything about it, thus the learning process involves a lot of persistence and trial and error. So I am really grateful for the pointers I get from this forum.

As it happens I am quite glad that I now have two methods at my disposal, and for the larger problem that I am working finding partial matches will also be very useful, and I will ultimately incorporate both approaches in my code. Cheers.

snb_

Well-known Member


  • #8

Code:

Sub M_snb()
    On Error Resume Next
    With New Collection
      .Add "aaa", "bbb"
      x3 = .Item("bb1")
      If Err.Number <> 0 Then MsgBox "item doesn't exist"
    End With
End Sub

  • #9

You’re welcome. Thanks for the feedback.

  • #10

As long as your ‘arr’ variable will always be a one-dimensional array, you could write your function this way…

Code:

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = InStr(Chr(1) & Join(arr, Chr(1)) & Chr(1), Chr(1) & stringToBeFound & Chr(1)) > 0
End Function

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

У меня есть код ниже, который должен проверять, находится ли значение в массиве или нет.

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").Value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").Value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

Если ячейка A1 содержит слово Examples, по какой-то причине обе IsInArray обнаруживают ее как существующую для обоих массивов, когда она должна находить ее только в массиве vars1

Что мне нужно изменить, чтобы сделать мою функцию IsInArray для ее точного соответствия?

4b9b3361

Ответ 1

Вы можете грубо заставить ее так:

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function

Использовать как

IsInArray("example", Array("example", "someother text", "more things", "and another"))

Ответ 2

Этот вопрос задавали здесь: массивы VBA — проверьте строковое (не аппроксимативное) соответствие

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Ответ 3

Используйте функцию Match() в excel VBA, чтобы проверить, существует ли значение в массиве.

Sub test()
    Dim x As Long

    vars1 = Array("Abc", "Xyz", "Examples")
    vars2 = Array("Def", "IJK", "MNO")

    If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
        x = 1
    End If

    MsgBox x
End Sub

Ответ 4

Хотя это, по сути, просто ответ @Brad, я подумал, что, возможно, стоит включить слегка модифицированную функцию, которая будет возвращать индекс искомого элемента, если он существует в массиве. Если элемент отсутствует в массиве, он возвращает -1.

Вывод этого можно проверить так же, как функцию «in string», If InStr(...) > 0 Then, поэтому я сделал небольшую тестовую функцию под ней в качестве примера.

Option Explicit

Public Function IsInArrayIndex(stringToFind As String, arr As Variant) As Long

    IsInArrayIndex = -1

    Dim i As Long
    For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = stringToFind Then
            IsInArrayIndex = i
            Exit Function
        End If
    Next i

End Function

Sub test()

    Dim fruitArray As Variant
    fruitArray = Array("orange", "apple", "banana", "berry")

    Dim result As Long
    result = IsInArrayIndex("apple", fruitArray)

    If result >= 0 Then
        Debug.Print chr(34) & fruitArray(result) & chr(34) & " exists in array at index " & result
    Else
        Debug.Print "does not exist in array"
    End If

End Sub

Затем я пошел немного за борт и выделил один для двухмерных массивов, потому что, когда вы генерируете массив на основе диапазона, он обычно в этой форме.

Он возвращает один вариантный массив измерений только с двумя значениями, два индекса массива используются в качестве входных данных (при условии, что значение найдено). Если значение не найдено, возвращается массив (-1, -1).

Option Explicit

Public Function IsInArray2DIndex(stringToFind As String, arr As Variant) As Variant

    IsInArray2DIndex= Array(-1, -1)

    Dim i As Long
    Dim j As Long

    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If arr(i, j) = stringToFind Then
                IsInArray2DIndex= Array(i, j)
                Exit Function
            End If
        Next j
    Next i

End Function

Вот картина данных, которые я настроил для теста, а затем тест:

test 2

Sub test2()

    Dim fruitArray2D As Variant
    fruitArray2D = sheets("Sheet1").Range("A1:B2").value

    Dim result As Variant
    result = IsInArray2DIndex("apple", fruitArray2D)

    If result(0) >= 0 And result(1) >= 0 Then
        Debug.Print chr(34) & fruitArray2D(result(0), result(1)) & chr(34) & " exists in array at row: " & result(0) & ", col: " & result(1)
    Else
        Debug.Print "does not exist in array"
    End If

End Sub

Ответ 5

Приведенная ниже функция возвращает 0, если совпадения нет, и положительное целое в случае совпадения:


Function IsInArray(stringToBeFound As String, arr As Variant) As Integer IsInArray = InStr(Join(arr, ""), stringToBeFound) End Function ______________________________________________________________________________

Примечание: функция сначала объединяет содержимое всего массива со строкой, используя ‘Join’ (не уверен, использует ли метод join внутреннее или нет циклическое выполнение), а затем проверяет наличие macth внутри этой строки, используя InStr.

Ответ 6

Я хотел бы предоставить еще один вариант, который должен быть и производительным и мощным, потому что

  • он не использует иногда более медленный Match)
  • поддерживает String, Integer, Boolean и т.д. (не String -only)
  • возвращает индекс искомого элемента
  • поддерживает nth-вхождение

'-1 if not found
'https://stackoverflow.com/a/56327647/1915920
Public Function IsInArray( _
  item As Variant, _
  arr As Variant, _
  Optional nthOccurrence As Long = 1 _
  ) As Long

    IsInArray = -1

    Dim i As Long:  For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = item Then
            If nthOccurrence > 1 Then
                nthOccurrence = nthOccurrence - 1
                GoTo continue
            End If
            IsInArray = i
            Exit Function
        End If
continue:
    Next i

End Function

используйте это так:

Sub testInt()
  Debug.Print IsInArray(2, Array(1, 2, 3))  '=> 1
End Sub

Sub testString1()
  Debug.Print IsInArray("b", Array("a", "b", "c", "a"))  '=> 1
End Sub

Sub testString2()
  Debug.Print IsInArray("b", Array("a", "b", "c", "b"), 2)  '=> 3
End Sub

Sub testBool1()
  Debug.Print IsInArray(False, Array(True, False, True))  '=> 1
End Sub

Sub testBool2()
  Debug.Print IsInArray(True, Array(True, False, True), 2)  '=> 2
End Sub

Ответ 7

Вы хотите проверить, существует ли Примеры в Range ( «A1» ). Значение Если это не удается, проверьте правильность Пример. Я думаю, что mycode будет работать идеально. Пожалуйста, проверьте.

Sub test()
Dim string1 As String, string2 As String
string1 = "Examples"
string2 = "Example"
If InStr(1, Range("A1").Value, string1) > 0 Then
    x = 1
ElseIf InStr(1, Range("A1").Value, string2) > 0 Then
    x = 2
End If

Конец Sub

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

Sep 2, 2013

I have a test to see if a text string is in an array that mostly works, but sometimes fails and I don’t understand why.

The routine calls a Function IsInArray which returns a True/False value depending on whether the search term is in the array.

Code:
Sub TestFilterArray()
MyArray = Array(«a», «b», «c»)
If IsInArray(«a», MyArray) = False Then

[Code]….

In this case the first item in my array is «a — b» (note that this is a text string ), but for some reason because my test value is «a» the routine things it must be in the array.

Thus I am thinking that the ampersand and dash symbols are somehow confusing my routine.

How can I change my routine so that it correctly identifies which text strings are in my array?

View 9 Replies

ADVERTISEMENT

VBA Find Partial String In Array And Output Found String Array Value?

Mar 31, 2014

I am trying to do a sort of index match thing using VBA. What I am attempting to do is to use the prefix of a long number and try to find that exact prefix in a string array, and output that string array value. So this is what I have so far as a test:

[Code]…..

So I can match the text exactly so if I put PREFIXB in cell A1 in this example, i will get the msg box saying «YES», but if I make it PREFIXB1231k4j3jj1kj32cj, it will display «NO». I want to get it so that PREFIXB will be displayed in the cell that I put the formula in. So if A1 = «PREFIX1AAA100CF» and cell B1 = «=ABC(A1)», cell B1 will display «PREFIX1AAA».

Now the thing is that these prefixes can have different lengths, but will never encompass the exact prefix of another. So if I had a prefix of: PRE1AB, I won’t have a prefix of PRE1A.

View 2 Replies
View Related

Excel 2007 :: Create String From Array?

Jul 23, 2012

I have this formula, ( which i found the basis of on a You tube video and Richard Scholar was accredited with improving the soloution)

=SUMPRODUCT(—ISNUMBER(F4:AH4)*10^{-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1})

This forumla generates a number for each player, the higher the number the more inline they are to get a game

Problems are this works for the 29 weeks of this year but more weeks need added to the end of the year as we get there. Can i generate the array numbers from a formula and shorten.

This is a sample data ignore row 2( just a count of players) and data actually goes back to 6th Jan

Excel 2007BCDEFGHIJ1Wk21Wk22Wk23Wk24Wk25Wk26Wk27Wk28210101010101010103Player 1111104Player 210001105Player 300101016Player 4010101107Player 50110118Player 600009Player 7111000110Player 8011100011Player 9000012Player 101011113Player 11101114Player 121010115Player 13016Player 141010017Player 15118Player 160101Sheet1

View 7 Replies
View Related

Copy Entire Excel Sheet Cells Values Into String Array?

Mar 3, 2014

How to copy the content of cells from an excell->sheet1 to an string array

View 2 Replies
View Related

Treating String As Array And Correct Array Format For Unicode Characters?

Jul 30, 2012

in C a string is nothing more than an Array of characters ending with a null character.

in VBA this does not seem to be the case.I am trying to use the BlowFish code from David Midkiff for some encryption, however the code sometimes fails:

When encrypting a string a string of a specific length should be returned. however sometimes one of the characters of the encrypted string is a null character, and the returned encrypted string (with a embedded null character) is causing me problems. I want to check for the null character and if present redo the encryption. But how do I check for the presence of this null character in a unicode (double-byte) string?

Checking with Len(encrypted) gives the correct length (!) but trying to move each (unicode)character into an array fails when using the Mid() function past the null character in the string.

Now I can use

byteArray() = StrConv(unicodetext,vbFromUnicode)

to get the lower byte of each character into an array easily, but how do I do this for both bytes of the unicode characters?

Using an integer array does not work other than through

intArray(j) = CInt(AscW(Mid(Outp, j, 1)))

which fails on the nullstring in my encrypted text.

I have tried with variants but so far no luck. I thought if the string was entered into a variant then I could also address the variant as an array of bytes, but that does not seem to be accepted by VBA.

View 1 Replies
View Related

Search Substring Of Array Matching List Of String From Another Array?

Dec 20, 2013

I need to export this to Xcelsius which doesn’t support any macros/vba. Btw I can;’t use Row() in xcelsius too.

[Code]…..

View 4 Replies
View Related

String Array Values To Array Of User-Defined Types

Oct 2, 2008

I have a class module with several private variables, including one that is an array of a user-defined type. I am trying to set the values of a single element of this array with «Property Let …» from a string array:

View 4 Replies
View Related

Check If Array Is Set

Apr 29, 2007

I would like to know if there is a straight forward way to check if dynamic array is set (initialized)? Is Nothing doesnt work with arrays and I dont want to use On Error GoTo becouse I dont like making jumps inside code. Sorry for this simple question but there is nothing about this in book i use and I couldnt find it in this forum.

View 8 Replies
View Related

Check Whether String Contains One Of Many Sub-strings

Nov 11, 2010

I’d like to write a formula that check if a string (contained in another cell — say A1) includes at least one occurrence of one of a set of 5 sub strings. If the substring is included then it should return which one.

For istance, say that the cell A1 = » The colour is BLACK» then I’d like a formula in cell B1 that check if any of the following strings is included in A1 (RED, GREEN, BLUE, BLACK, ORANGE) and that tells me which one.

How to do this with a one cell formula ?

View 6 Replies
View Related

Check Last 4 Letter Of A String

Nov 18, 2008

how I check the last 4 letters of a String to make sure they say ‘.xls’, ‘.csv’, etc, etc, for varification purposes.

View 4 Replies
View Related

Check If Cell Contains A Particular String

Apr 21, 2009

My question is about checking to see if a cell contains a particular word.

I know that the following checks to see if a cell’s value IS a particular word:

View 2 Replies
View Related

Check If String Contains A Number

Sep 25, 2009

Is there way in Excel VBA to check if a string contains a number, and then return TRUE or FALSE. Numbers can been anywhere in the string. See example below.

View 6 Replies
View Related

Check If String Contains Only Digits

Apr 19, 2008

I’m working on a project where I need to prevent the user from entering non-digit string inputs. I’ve tried the using IsNumeric(MyString). but that doesn’t prevent , + — signs to be entered. I also had to conditionally enable the input of a string with leading zeros like «01» so what I’ve ended up with is a rather messy looking’ sub that handles this (don’t know if forum rules allows me to show it here?). The problem is that I’m not a 100% sure that my sub fit to handle all eventualities so therefore my question is whether there is an easier, fool proof way to check my strings?

View 6 Replies
View Related

Array To Check Cells

Oct 7, 2011

I have the following code that i want to use to run trough a few checkboxes to check the value and then wright something in a cell. i have written the the checkbox name to a variable and then want to use it in the if command but gives me a type mismach.

Code:
Dim CheckBox As String
For i = 1 To 204
For c = 3 To 227
CheckBox = «Sheet3.CheckBox» & i & «.Value»
If CheckBox = True Then
Range(«J» & c) = «Done»
Else
Range(«J» & c) = «»
End If
Next
Next

View 9 Replies
View Related

How To Check If Array Is Empty

Mar 1, 2014

Secondly, I am struggling to find a solution to something that in PHP, Java and javascript is painfully simple! That is — checking to see if an array contains no elements.

In PHP for example, you can do:

PHP Code:
$arr = array();echo empty($arr).»
«;echo (sizeof($arr) == 0).»
«; 

This will produce the following output:

Code:
1
1

But … I can’t seem to find any equivalent of empty or sizeof in VBA.

View 4 Replies
View Related

Check If Value Exists In An Array

Sep 10, 2007

Is there a way that I can check for the occurance of a specific value in a collection object like an Array or a Range in excel through VBA code?

For example I would like to check programatically if the value «orange» is present in an array by name Fruits(), where the array Fruits (3)=(«mango», «banana», «apple»).

View 9 Replies
View Related

How To Check Multiple Cells Have Same String

Jul 9, 2013

I want to check if cells C1, D1 and E1 contain the same name. For example if the cells all contain the ‘Joe Bloggs’ (or whatever the name variable happens to be) then cell F1 should say «Yes», else «No».

View 1 Replies
View Related

Check If First 5 Digits Of String Are Numeric

May 23, 2007

I have some code where I need to check if the first five char are numbers and not letters.

I have in a column for example
12345-someone is here
23456-someone else is here
someone is here too

I need to get all of the ones that have 5 digits and not pull in the other into a new list.

I have tried Left(CPHierAll. Cells(CPHierAllRow, 1),5) which will get me the fist 5 char. and then i need to check to make sure that they are all numbers and not char.

if Left(CPHierAll.Cells(CPHierAllRow, 1),5) = «#####» then
But this does not bring anything in.

I also tried if CPHierAll.Cells(CPHierAllRow, 1),5) = «#####» then

I have 3 column that i am checking for different thinks the first two work just find and seperate out on the check but the last one with the numbers is being a pain.

View 9 Replies
View Related

Excel — UDF That Returns String Of Multiple String Objects / Possible To Color Font?

Sep 19, 2012

I have a udf that returns a string to the cell. The string is made up of multiple string «objects». What I am wondering is if I can set the font color of certain objects so that when the final string is built and returned, the font of those portions is set.

Ex. of simple idea (this is not actually my code, just a way to illustrate. I realize there is no point to this UDF):

VB:

Function StringReturn (Str1 As String, Str2 As String, Str3 As String) As String
StringReturn = Str1 & Str2 & Str3
End Function

Now what if I wanted Str1 and Str3 to be blue, and Str2 to be red for example. So that when the UDF calculates it would return: Str1Str2Str3

View 2 Replies
View Related

Check If String Is Single Cell Reference

Jul 6, 2008

I’d like to check if a user supplied string is single cell reference. My problem is that the below code comes back as vallid if I enter a range like B2:B4.

Sub test2()

Dim UserAdd As String
UserAdd = InputBox(«Enter your address»)

‘check if valid:
If ValidAddress(UserAdd) Then
MsgBox («it’s valid!»)
Else
MsgBox («it ain’t valid!»)
End If

End Sub

View 9 Replies
View Related

Array To Check User Input Match

Feb 22, 2007

This is what i want to do: SEE ATTACHEMENT

�Write codes to pop up an InputBox to ask the user for a customer name.

�The program uses the user�s input to check whether the name is on the list. If it is, display an msgbox saying that the customer name is on the list, and the corresponding cell will be indicated in boldface and in blue. Otherwise, an msgbox will be displayed saying that the customer name is not on the list.

Dim the customer list as an array (string var. type) and Dim Found as Boolean. You will need the If-Then construction and For-Next or Do-While/Until loop too). Create a button to run and another to restore the formatting to its original style.

This is what i did so far and still having problems with it:

Option Explicit

Sub customers()

Dim Arr()
Dim R As Integer
Dim C As Integer
Dim ReturnColumn As Boolean

View 6 Replies
View Related

Partial String Check In Cell Against Range For Return

Feb 15, 2010

I’ve posted this query before, not on this forum, but I don’t think the replies I’ve had so far are going to do what I want. Initially I was looking for a formula, but the suggested pile of nested IFs won’t work for the number of conditions. I saw a previous post on here for a VBA macro to search for a text value in a cell against the cell contents of a range and it seemed to do at least the first part of what I wanted. I attempted to manipulate it a little to test its applicability for my own nefarious purposes but for the life of me I can’t get it working.

This is complicated by the fact that the actual data is commercially confidential, so I can’t show you the actual file, but I can fake what I want with two simpler ones. I’ve attached them to this post. What I want is a fair bit more complex than the other post I found — I want to be able to compare a partial text string from a given cell in a range (‘Check Value’ in the attached TestBook2 ) against the strings in a range of cells (‘Value 1’ in TestBook1), and return the corresponding value from ‘Test Value’ to the corresponding adjacent cell to the tested ‘Check Value’, with an order of precedence, for example…

Testbook2 contains an entry in C5 of ‘a, e, h, z, x, y’. Testbook1 shows that the return for a, b, c, or d is ‘moo’, for e, f, or g is ‘steve’ and for g through q is ‘fred’, all others being no returned value. Moo>steve>fred, so I want the corresponding ‘moo, steve. fred or <blank>’ cell to contain ‘moo’. Conversely, C6 contains ‘t, u, z’ and therefore shouldn’t have a value in ‘moo, steve, fred or <blank>’. C12 contains ‘f, z, s, y, u’ and C15 ‘i, x, z, s’, and therefore should display ‘steve’ and ‘fred’ respectively.

View 3 Replies
View Related

Regular Expression: Check If A String Has A Sequence Of 6 Decimal Digits

Apr 13, 2007

I am using the following to check if a string has a sequence of 6 decimal digits in it. But am getting an error. If(str Like *######*). I have to check if str has values like 123456USA ; ABC725439 ; jh658478hd. I thought # represents a single digit and * represents any no of characters

View 2 Replies
View Related

Finding String In Array

Aug 8, 2013

I have list of strings to be searched in column A2 to A150 (A1 has column title). The array that needs to be searched is in B2 to AG1000 (B1 to AG1 has column title). I want each string in column A to be searched in the full array. If match is found the corresponding column title (B1 or C1 and so.) and cell address needs to written to a new result columns in AY and AZ. it should work for duplicates as well i.e. the string can be in all the columns of array from B to AG. and all of them needs to be written to result column.

View 9 Replies
View Related

If String Equals Value In Array?

Sep 26, 2013

I’m trying to verify if a cellvalue is available in an array. Here is the code:

First I tried to check if the cellval is in the array by returning a -1, 0 or 1:

Code:
If UBound(txt, cellval) = 0 Then
-> returns zero for value «h3», but also for value «3»
(where cellval the value in the cell is)
(with txt being the array containing «h3,r8,ty657», etc)

But I need only the If to be true when there is an exact match.

View 2 Replies
View Related

Array As String And Integer Together

Sep 19, 2007

I have defined array say like this:
Dim myarray (1 to 5, 1 to 2)

Is possible to define something like this?
myarray (x, 1) as string
myarray (x, 2) as integer

x is anything between 1 to 5 .

View 9 Replies
View Related

Split String Into Array

Sep 20, 2008

Say I have a string, «a test array.» I want to split this into an array where each character is an element. I was thinking something like

Dim MyArray As Variant
Dim MyString As String
MyString = «a test array»
MyArray = Split(MyString, «», Len(MyString), vbTextCompare)

But this doesn’t work because Split() returns the entire string when the delimiter is a zero-length string.

View 9 Replies
View Related

Passing Array Of UDT With String To C++ Dll

Feb 17, 2009

I’m trying to pass an array of UDT from Excel to a C++ dll but I have no idea how. My UDT looks like this

Private Type Student
Age As Integer
Name As String
StudentID As String
End Type
And my dll function declaration..

Declare Function RegisterStudent Lib «SimpleDLL.dll» _
(arr() as Student) As String
.. which will return a unique Id in string

View 9 Replies
View Related

Sort String Array

Nov 18, 2006

I have a string (PreString) that gets its values from a procedure call (PreResult). The string consists of 4 values for each loop which I then split into the y array.

I then want to transpose the array to the worksheet for sorting.

I don’t really get the transpose to work as I want to. I want every 4:th y to be printed on a new row (x). I don’t really know how to use the Ubound function to get it right.

Should I make a 2 dimensional array instead ? If so, how is that made ?

Dim x As Integer, z As Integer
Dim var_Status As Integer
Dim var_Week As String
Dim var_HoursPerWeek As Integer
Dim PreString As String

i = var_StartWeekNr
j = var_RangeNumberOfWeeks
z = 0
x = 0
var_Status = 0
var_Week = «»
var_HoursPerWeek = 0
PreString = «»

View 8 Replies
View Related

Extract Data From A String Array And Sum

Nov 9, 2009

I want to extract data from array string and then sum the values. For reference attaching the excel.

View 14 Replies
View Related

Like this post? Please share to your friends:
  • Excel vba string array to string
  • Excel vba str to int
  • Excel vba stop vba
  • Excel vba stop for
  • Excel vba sql not in