Excel VBA用户表单使用复选框将数据输入多行

时间:2018-08-10 03:06:48

标签: excel excel-vba checkbox userform

您好,我需要根据选中的复选框一次输入多行数据。当前,这仅添加1行。我认为我必须使用循环,但不确定如何实现。有人可以帮忙吗?

Userform

示例输出应如下所示:

TC37    | 1
TC37    | 2
TC37    | 4

当前代码:

Dim LastRow As Long, ws As Worksheet
Private Sub CommandButton1_Click()

  Set ws = Sheets("sheet1")

  LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1

  ws.Range("A" & LastRow).Value = ComboBox1.Text

  If CheckBox1.Value = True Then
    ws.Range("B" & LastRow).Value = "1"
  End If

  If CheckBox2.Value = True Then
    ws.Range("B" & LastRow).Value = "2"
  End If

  If CheckBox3.Value = True Then
    ws.Range("B" & LastRow).Value = "3"
  End If

  If CheckBox4.Value = True Then
    ws.Range("B" & LastRow).Value = "4"
  End If

End Sub

Private Sub UserForm_Initialize()
  ComboBox1.List = Array("TC37", "TC38", "TC39", "TC40")
End Sub

2 个答案:

答案 0 :(得分:2)

由于您最后一次获得了1行,因此应该转储与该行相关的数据。尝试类似的东西:

Dim chkCnt As Integer
Dim ctl As MSForms.Control, i As Integer, lr As Long
Dim cb As MSForms.CheckBox

With Me
    '/* check if something is checked */
    chkCnt = .CheckBox1.Value + .CheckBox2.Value + .CheckBox3.Value + .CheckBox4.Value
    chkCnt = Abs(chkCnt)
    '/* check if something is checked and selected */
    If chkCnt <> 0 And .ComboBox1 <> "" Then
        ReDim mval(1 To chkCnt, 1 To 2)
        i = 1
        '/* dump values to array */
        For Each ctl In .Controls
            If TypeOf ctl Is MSForms.CheckBox Then
                Set cb = ctl
                If cb Then
                    mval(i, 1) = .ComboBox1.Value
                    mval(i, 2) = cb.Caption
                    i = i + 1
                End If
            End If
        Next
    End If
End With
'/* dump array to sheet */
With Sheets("Sheet1") 'Sheet1
    lr = .Range("A" & .Rows.Count).End(xlUp).Row + 1
    .Range("A" & lr).Resize(UBound(mval, 1), 2) = mval
End With

答案 1 :(得分:1)

问题是您的变量LastRow不会更改。一开始仅设置一次。因此,当您尝试写入该值时,它将始终将其写入同一单元格。

If CheckBox1.Value = True Then
    LastRow = ws.Range("B100").end(xlup).Row + 1  
    ws.Range("B" & LastRow).Value = "1"
End If

If CheckBox2.Value = True Then
    LastRow = ws.Range("B100").end(xlup).Row + 1
    ws.Range("B" & LastRow).Value = "2"
End If

If CheckBox3.Value = True Then
    LastRow = ws.Range("B100").end(xlup).Row + 1
    ws.Range("B" & LastRow).Value = "3"
End If

If CheckBox4.Value = True Then
    LastRow = ws.Range("B100").end(xlup).Row + 1
    ws.Range("B" & LastRow).Value = "4"
End If

您还可以使用and数组存储值,然后将数组的结果粘贴到范围中。

有很多方法可以做到这一点,但是这一方法应该可行。在粘贴值之前,应始终清除范围。

希望这会有所帮助,