问题
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 ?
回答1:
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
回答2:
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)
回答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
来源:https://stackoverflow.com/questions/63289592/ucase-for-each-statement