Search code examples
excelvbastringloopsdata-collection

VBA Setting string value with changing string name


Hi I'm trying to create macro that will collect data from excell table. I create strings with similar names and ended by number. Please is there a way to loop over this strings ? This Code is not working, but will explain what I want to do.

Sub vzor()

Dim i As Integer

Dim input1, input2, input3, input4, input5, input6, input7, _
input8, input9, input10, input11, input12, input13, input14, _
input15, input16, input17, input18, input19, input20, input21, _
input22, input23, input24, input25, input26, input27, input28, _
input29, input30, input31, input32, input33, input34, input35, _
input36, input37, input38, input39, input40, input41, input42, _
input43, input44, input45, input46, input47, input48, input49, _
input50, input51, input52, input53, input54, input55, input56, _
input57, input58, input59, input60, input61, input62, input63, _
input64, input65, input66, input67 As String

For i = 2 To 67

    If Range("B" & i).Value = "" Then
        MsgBox "Please fill all required data (The cells with red fill)", vbOKOnly, "Missing data"
        Range("B" & i).Select
    Else
         input & i = Range("B" & i).Value
    End If

Next

Solution

  • This seems to be a perfect example for a dictionary

    Option Explicit
    
    Dim wb As Workbook, ws As Worksheet
    Dim inputdict As Variant
    Dim i As Long
    
    Set inputdict = CreateObject("Scripting.Dictionary")
    Set wb = ThisWorkbook 'Change if necessary
    Set ws = wb.Sheets(1) 'Change if necessary
    
    For i = 1 To 67
        If ws.Cells(i, "B").Value = vbNullString Then
            MsgBox "Please fill all required data (The cells with red fill)", vbOKOnly, "Missing data"
            ws.Cells(i, "B").Select
        Else
            inputdict.Add i, ws.Cells(i, "B").Value
        End If
    Next i
    

    This creates a dictionary (inputdict). The keys for this dictionary are integers defined by i ranging from 1 to 67. The values are the values in the cells as you specified in your code already.