取消选中最后选择的复选框

问题描述 投票:0回答:1

我有 2 张桌子,但计划添加更多。我希望 vba 取消标记最后选定的复选框,无论它是在表 1 还是表 2 中。

每个表格有 4 列,从 D 列中的复选框开始,E 列为商品代码,F 列为描述,G 列为数量。我已经删除了所有链接的单元格属性以获得干净的状态。我确实有一个代码可以将所有复选框链接到其各自的单元格。

我遇到的问题是,允许标记的复选框的最大数量应该是 27,一旦标记了第 28 个复选框,就应该取消标记它,并且应该出现一个消息框,向用户发出警告。我尝试过使用 ChatGpt,但它提供的代码要么取消标记表 1 中的第一个复选框,要么取消标记表 2 中的最后一个复选框。任何帮助将不胜感激。下面来自 ChatGpt 的代码:

Private Sub Worksheet_Calculate()
Dim checkbox As checkbox
Dim checkedCheckboxes As Collection
Dim maxChecked As Integer
Dim totalChecked As Integer

Maximum number of checkboxes allowed in total
maxChecked = 27

Initialize the collection to store checked checkboxes
Set checkedCheckboxes = New Collection

Loop through each checkbox in the worksheet
For Each checkbox In Me.CheckBoxes
Check if the checkbox is checked
If checkbox.Value = xlOn Then
Add the checked checkbox to the collection
checkedCheckboxes.Add checkbox
End If
Next checkbox

Calculate the total count of checked checkboxes
totalChecked = checkedCheckboxes.Count

Check if the total count exceeds the maximum allowed
If totalChecked > maxChecked Then
Uncheck the last checked checkbox
checkedCheckboxes(1).Value = xlOff
checkedCheckboxes.Remove 1

Display a message
MsgBox "Reservation in SAP only has 27 lines. Please transfer data and clear checkboxes to continue!", vbInformation, "Result Check"
End If
End Sub

excel vba checkbox
1个回答
0
投票

理想情况下,您首先不要让用户选择太多复选框 - 如果他们必须在提交之前返回并取消选择复选框,那么这只会让他们的生活变得更加困难......

如果您将其放入常规模块中并将所有复选框链接到它,以便单击运行代码,那么一旦达到该工作表的限制,它将禁用复选框:

Sub LimitCheckboxes()
    
    Const MAX_CHECKED As Long = 3
    Dim cb As CheckBox, colOn As Collection, colOff As Collection, atLimit As Boolean
    
    Set colOn = New Collection
    Set colOff = New Collection
    For Each cb In Sheet2.CheckBoxes
        If cb.Value = xlOn Then
            colOn.Add cb
        Else
            colOff.Add cb
        End If
    Next cb
    
    atLimit = (colOn.Count = MAX_CHECKED)
    For Each cb In colOff
        cb.Interior.Color = IIf(atLimit, RGB(200, 200, 200), vbWhite)
        cb.Enabled = Not atLimit
    Next cb

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.