Search code examples
excelvbacopyuserform

Copying data from Userform CheckBox and Textbox to columns


I am trying to create a tool with a userform where the user types a Model in a textbox and selects all the countries where this Model comes from in 10 possible checkboxes.

This information is transferred to "Country" Worksheet through command button.

My code places textbox value in column A and country name from checkbox label in column B.
The problem is that I have more than one country for the same model so I'm getting blank cells without matching Model.
E.g. "Type A" belongs to USA, Brazil, Sweden and Mexico, so I should have "Type A" copied four times along country names instead of just one.

Private sub Transfer()
    
    Dim i As Long
    Dim aCol As Range
    Dim BS As Worksheet
    
    Set aCol = Worksheets("Country").Range("A:A")
    Set BS = Worksheets("Country")
    
    For i = 1 To 10
        With Me.Controls("CheckBox" & i)
            If .Value Then
                aCol.Cells(82, 2).End(xlUp).Offset(1, 0).Value = .Caption
            End If
        End With
    Next i
    
    Dim b As Integer
    b = 1
        
    Do Until BS.Range("A" & b).Value = ""

    b = b + 1

end sub

Solution

  • With the code you shared and without major changes, I would suggest you to think about writing the info contained in the textbox within the loop of the checkboxes and right after the if. This way you will be adding the textbox text no matter what avoiding the blanks

    If .Value Then
        aCol.Cells(82, 1).End(xlUp).Offset(1, 0).Value = Me.Controls("TextBox1").Text
        aCol.Cells(82, 2).End(xlUp).Offset(1, 0).Value = .Caption
    End If
    

    Let me know if that works, below the full code I used to replicate your issue:

    Private Sub CommandButton1_Click()
    Call Transfer
    End Sub
    
    
    Private Sub Transfer()
    Dim i As Long
    Dim aCol As Range
    Dim BS As Worksheet
    
    Set aCol = Worksheets("Country").Range("A:A")
    Set BS = Worksheets("Country")
    
        For i = 1 To 3
            With Me.Controls("CheckBox" & i)
                If .Value Then
                    aCol.Cells(82, 1).End(xlUp).Offset(1, 0).Value = Me.Controls("TextBox1").Text
                    aCol.Cells(82, 2).End(xlUp).Offset(1, 0).Value = .Caption
                    
                End If
            End With
            Next i
    End Sub
    

    How the form I did looks in VBA

    How the results look like in the file