如何在 Excel VBA 中的列末尾制作用户表单输出

How to make User Form Output at the end of a column in Excel VBA

我试图让这个用户表单输出选项按钮结果在一列的末尾。最初我尝试在主模块中的 for next 循环中使用相同的 i,但用户表单无法识别该变量,即使在将其标注为 public 之后也是如此。有什么想法吗?

Private Sub cmdOk_Click()

If opt1 Then
    Range(Range(“E3”), Range(“E3”).End(xlDown)) = "None"
ElseIf opt2 Then
    Range(Range(“E3”), Range(“E3”).End(xlDown)) = "3/8 Plain"
ElseIf opt3 Then
    Range(Range(“E3”), Range(“E3”).End(xlDown)) = "1/2 Plain"
ElseIf opt4 Then
    Range(Range(“E3”), Range(“E3”).End(xlDown)) = "1/2 Herringbone"
ElseIf opt5 Then
    Range(Range(“E3”), Range(“E3”).End(xlDown)) = "1/2 Diamond"
End If

Unload frmLagging

End Sub

您需要找到该列的最后一行,然后写入。这是一个示例(未测试)。您可以阅读有关查找最后一行的更多信息 Here

Dim ws As Worksheet
Dim lRow As Long
Dim rng As Range

Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    '~~> We add 1 so that we get the next empty cell
    lRow = .Range("E" & .Rows.Count).End(xlUp).Row + 1

    Set rng = .Range("E" & lRow)

    If opt1 Then
        rng.Value = "None"
    ElseIf opt2 Then
        rng.Value = "3/8 Plain"
    ElseIf opt3 Then
        rng.Value = "1/2 Plain"
    ElseIf opt4 Then
        rng.Value = "1/2 Herringbone"
    ElseIf opt5 Then
        rng.Value = "1/2 Diamond"
    End If
End With
Unload frmLagging

此外, 这是我最喜欢的 iif 语句之一,

Private Sub CommandButton1_Click()
    Dim Rws As Long, Rng As Range, x
    Rws = Cells(Rows.Count, "E").End(xlUp).Row

    Set Rng = Cells(Rws + 1, "E")

    x = IIf(Opt1, "None", IIf(Opt2, "3/8 Plain", IIf(Opt3, "1/2 Plain", IIf(Opt4, "1/2 Herringbone", IIf(Opt5, "1/2 Diamond", "Nada")))))
    Rng = x

    Unload Me
End Sub