You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA如何激活UserForm的OptionButton(无需直接为其赋值)

错误原因

Frame.ActiveControl属性仅当Frame内的控件实际获得焦点(被手动点击激活)时才会返回有效对象,通过代码设置OptionButton.Value = True仅会修改选中状态,不会自动将焦点迁移到对应控件上。未手动选中过OptionButton时Frame3.ActiveControl为空对象,调用.Name属性就会抛出「Object Variable Or With Block Variable Not Set」错误。

最优解决方案

不要依赖激活状态判断,直接遍历Frame内的OptionButton定位选中项,代码稳定性更高,无需修改原有赋值逻辑:

Private Sub CommandButton1_Click()
    Dim opt As MSForms.OptionButton
    Dim selectedOptName As String
    
    ' 遍历Frame3内所有控件匹配选中的单选按钮
    For Each opt In Me.Frame3.Controls
        If TypeName(opt) = "OptionButton" And opt.Value = True Then
            selectedOptName = opt.Name
            Exit For
        End If
    Next
    
    Select Case selectedOptName
        Case "Name 1"
            'Code Path 1
        Case "Name 2"
            'Code Path 2    
    End Select
End Sub

可选兼容方案

如果希望保留原有ActiveControl的判断逻辑,只需在代码设置OptionButton选中状态的同时,调用SetFocus方法手动激活控件即可:

' 原有赋值逻辑后补充激活代码
OptionButton1.Value = True
OptionButton1.SetFocus

内容的提问来源于stack exchange,提问作者Milad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:54:04