Search code examples
arraysvbavariablesdynamicuserform

Dynamically extract text from a userform


I would like to extract the text from textboxes in a userform and store them as elements in an array. However, these textboxes have dynamic names and I cannot set the array elements because it stores them as a string.

'Loop through the sections to fill the array using a concatonated dynamic path
For Counter = 0 To numSections - 1

    'Fill in title, start page, end page
    sectionInfo(Counter, 0) = "UserForm1.TextInput" & CStr(Counter) & ".Text"

    sectionInfo(Counter, 1) = "UserForm1.pageStart" & CStr(Counter) & ".Text"

    sectionInfo(Counter, 2) = "UserForm1.pageEnd" & CStr(Counter) & ".Text"

Next Counter

How can I concatenate the string and pass it as a command and not a string? I am beginning to think that this is not possible as I have looked everywhere.


Solution

  • Use the Controls collection. Something like UserForm1.Controls("TextInput" & CStr(Counter)).Text and so on.

    'Loop through the sections to fill the array using a concatonated dynamic path
    For Counter = 0 To numSections - 1
        'Fill in title, start page, end page
        sectionInfo(Counter, 0) = UserForm1.Controls("TextInput" & CStr(Counter)).Text
        sectionInfo(Counter, 1) = UserForm1.Controls("pageStart" & CStr(Counter)).Text
        sectionInfo(Counter, 2) = UserForm1.Controls("pageEnd" & CStr(Counter)).Text
    Next Counter