excel - 在用户窗体 VBA 中使用带有选项按钮的 IF/Then 语句

标签 excel vba

有没有一种方法可以对选项按钮进行编码,以根据两者的选择给出一个值?我尝试了多种方法,但似乎一事无成。这是我尝试过的最后一个代码,如果可能的话,这就是我希望它工作的方式。这段代码现在的样子,我只得到一个值。

Private Sub OptBtn()

    Dim n As Long

    n = Sheets1.Range("A" & Application.Rows.Count).End(xlUp).Row
    Range("A" & Rows.Count).End(xlUp).Select
    ActiveCell.Offset(1, 0).Select
    ActiveCell.EntireRow.Insert


    If Me.OptBtn_AddCard.Value = True & Me.OptBtn_ManagedBy.Value = True Then
        Sheets1.Range("I" & n + 1).Value = "ACTIVE"

    Else

        If Me.OptBtn_AddCard.Value = True & Me.OptBtn_ManagedBy.Value = False Then
            Sheets1.Range("I" & n + 1).Value = "AVAILABLE"

        Else

            If Me.OptBtn_AddCard.Value = False & Me.OptBtn_ManagedBy.Value = True Then
                Sheets1.Range("I" & n + 1).Value = "ACTIVE"

            End If
        End If
    End If

End Sub

最佳答案

使用And而不是&

If Me.OptBtn_AddCard.Value = True And Me.OptBtn_ManagedBy.Value = True Then
    Sheets1.Range("I" & n + 1).Value = "ACTIVE"
Else
    If Me.OptBtn_AddCard.Value = True And Me.OptBtn_ManagedBy.Value = False Then
        Sheets1.Range("I" & n + 1).Value = "AVAILABLE"
    Else
        If Me.OptBtn_AddCard.Value = False And Me.OptBtn_ManagedBy.Value = True Then
            Sheets1.Range("I" & n + 1).Value = "ACTIVE"
        End If
    End If
End If

代码可以这样缩短:

If Me.OptBtn_AddCard.Value And Me.OptBtn_ManagedBy.Value Then
    Sheets1.Range("I" & n + 1).Value = "ACTIVE"
Else
    If Me.OptBtn_AddCard.Value And Not Me.OptBtn_ManagedBy.Value Then
        Sheets1.Range("I" & n + 1).Value = "AVAILABLE"
    Else
        If Not Me.OptBtn_AddCard.Value And Me.OptBtn_ManagedBy.Value Then
            Sheets1.Range("I" & n + 1).Value = "ACTIVE"
        End If
    End If
End If

我个人喜欢 Switch() 变体:

Switch function: Evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is True

Sheets1.Range("I" & n + 1).Value = Switch( _
    Me.OptBtn_AddCard.Value And Me.OptBtn_ManagedBy.Value, "ACTIVE", _
    Me.OptBtn_AddCard.Value And Not Me.OptBtn_ManagedBy.Value, "AVAILABLE", _
    Not Me.OptBtn_AddCard.Value And Me.OptBtn_ManagedBy.Value, "ACTIVE")

关于excel - 在用户窗体 VBA 中使用带有选项按钮的 IF/Then 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71597362/

相关文章:

vba - 在 Excel 中合并列

excel - Vba Excel 维护大数据列表的最佳方式

vba - 宏未按预期循环工作簿

vba - 取消链接图片超链接

vba - 使用集合作为类中的属性(参数不可选)

python - 如何将一个包含 +1.048.576 行的数据框导出到多个 Excel 文件/工作表中

excel - VBA POST 格式问题

vba - 200 个按钮全部更改一个文本框 - VBA Excel

vba - Application.ScreenUpdating 不会更改为 false

excel - Simpe VBA sub : Error on start of function, 但不是之后