2020年5月11日 星期一

Example - Loop Through the Alphabet with VBA

Example - Loop Through the Alphabet with VBA

Sub loopABC()
Dim FirstLetter As String * 1
Dim CapitalLetters As Boolean
Dim NumberOfLetters As Integer
Dim ichr, i, icount As Integer
Dim Letter As String * 1

'------------------------
'USER INPUT
FirstLetter = "A"        'the letter you want to start with
CapitalLetters = True    'set to True if you want capital letters (A B C). False if you want lowercase (a b c)
NumberOfLetters = 26     'number of letters you want to loop through
'END OF INPUT
'------------------------

If CapitalLetters = True Then FirstLetter = UCase(FirstLetter)
If CapitalLetters = False Then FirstLetter = LCase(FirstLetter)
ichr = Asc(FirstLetter)
For i = 1 To NumberOfLetters
    If CapitalLetters = True Then
        If ichr > 90 Then ichr = 64 + ichr - 90
        Letter = Chr(ichr)
    Else
        If ichr > 122 Then ichr = 96 + ichr - 122
        Letter = Chr(ichr)
    End If
    ichr = ichr + 1
    '---------------------------------------------
    'USER ACTION
    ' Your letter is stored in the variable Letter.
    ' Do what you want with it here.
    ' For example: Range("A" & i) = Letter
    '---------------------------------------------
Next i
End Sub

沒有留言:

張貼留言