0

I am trying to convert a string that may contain numbers to UpperCase using UCase. When I used a line like that

For Each vLetter In UCase(lName)

I encountered an error when the lName variable equals to "Yasser51" as an example. How can I overcome this ?

YasserKhalil
  • 9,138
  • 7
  • 36
  • 95

3 Answers3

4

You can't use For Each like this. For Each can only iterate over a collection or an array. A String is neither.

One option to loop character-by-character is Mid$ and a regular For loop. (Though it's still unclear what you're actually trying to do and if a loop is even required):

Sub Test()
    Dim lName As String
    lName = "Yasser51"
    
    Dim i As Long
    For i = 1 To Len(lName)
        Dim letter As String
        letter = Mid$(UCase(lName), i, 1)
        
        Debug.Print letter
    Next
End Sub
BigBen
  • 46,229
  • 7
  • 24
  • 40
3

To convert to upper case you simply use UCase. If you want to iterate then see @BigBen's answer.

Dim sName as String
Dim sUpper as String

sName = "Yasser51"
sUpper = UCase(sName)
Super Symmetry
  • 2,837
  • 1
  • 6
  • 17
3

Addendum

As mentioned a string is neither a collection nor an array, however you can assign a string to a ► Byte array that can be iterated easily via a For Each loop.

Note that the Byte array always contains pairs of bytes with numeric values; so for example digits 0-9 are shown as numeric Asc values between 48-57 (together with value 0 as further companion value), similar for usual letter characters A-Z and a-z.

Sub IterateByte()
Dim s   As String: s = "Yasser51"
Dim b() As Byte: b = s

Debug.Print " i", "Asc Value ", "ch| IsDigit" & vbNewLine & String(50, "-")

Dim i As Long, ch As String, vNum As Variant
For Each vNum In b
    ch = Chr(vNum)
    If vNum Then Debug.Print i, "Asc " & vNum, ch & " | " & (ch Like "#")
    i = i + 1
Next
End Sub

Example result in VB Editor's immediate window

' i            Asc Value     Ch| IsDigit
'--------------------------------------------------
' 0            Asc 89        Y | False
' 2            Asc 97        a | False
' 4            Asc 115       s | False
' 6            Asc 115       s | False
' 8            Asc 101       e | False
' 10           Asc 114       r | False
' 12           Asc 53        5 | True
' 14           Asc 49        1 | True
T.M.
  • 9,436
  • 3
  • 33
  • 57
  • 1
    FYI You might as well be interested in a tricky way to get a digits array at [Divide numbers into unique sorted digits](https://stackoverflow.com/questions/63540928/divide-numbers-into-unique-sorted-digits-displayed-in-a-label-on-a-userform/63546848#63546848 ) - @YasserKhalil – T.M. Aug 24 '20 at 18:57