Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 10009|回复: 14

[已解决]VBA窗体中有好几个选项按钮,该如何返回“选择了哪个按钮”

[复制链接]
发表于 2012-10-18 10:59 | 显示全部楼层 |阅读模式
快照1.jpg
如图所示:我如果选中一个按钮,再点“确定”的话,如何用msgbox或在A1单元格中返回按钮的名称? 示例.zip (7.74 KB, 下载次数: 27)
发表于 2012-10-18 11:16 | 显示全部楼层
Private Sub CommandButton1_Click()
    If Me.OptionButton1 = True Then
        MsgBox Me.OptionButton1.Name
    ElseIf Me.OptionButton2 = True Then
        MsgBox Me.OptionButton2.Name
    ElseIf Me.OptionButton3 = True Then
        MsgBox Me.OptionButton3.Name
    ElseIf Me.OptionButton4 = True Then
        MsgBox Me.OptionButton4.Name
    ElseIf Me.OptionButton5 = True Then
        MsgBox Me.OptionButton5.Name
    ElseIf Me.OptionButton6 = True Then
        MsgBox Me.OptionButton6.Name
    ElseIf Me.OptionButton7 = True Then
        MsgBox Me.OptionButton7.Name
    ElseIf Me.OptionButton8 = True Then
        MsgBox Me.OptionButton8.Name
    End If
End Sub



俺只会笨办法
回复

使用道具 举报

发表于 2012-10-18 11:24 | 显示全部楼层
  1. Private Sub CommandButton1_Click()
  2.     Dim mycontrol As Control
  3.     For Each mycontrol In Me.Controls
  4.         If TypeName(mycontrol) = "OptionButton" And mycontrol.Value = -1 Then
  5.             MsgBox mycontrol.Name
  6.             Exit For
  7.         End If
  8.     Next
  9. End Sub
复制代码
按钮代码
回复

使用道具 举报

 楼主| 发表于 2012-10-18 11:38 | 显示全部楼层
hwc2ycy 发表于 2012-10-18 11:24
按钮代码

出现错误 快照2.jpg
回复

使用道具 举报

发表于 2012-10-18 11:51 | 显示全部楼层
Private Sub CommandButton1_Click()
    Dim mycontrol As Control
   on error resume next
    For Each mycontrol In Me.Controls
        If TypeName(mycontrol) = "OptionButton" then
            if  mycontrol.Value = true Then
                   MsgBox mycontrol.Name & "-----"  & mycontrol.caption
                   Exit For
           end if
        End If
    Next
End Sub
回复

使用道具 举报

 楼主| 发表于 2012-10-18 12:06 | 显示全部楼层
extyg 发表于 2012-10-18 11:51
Private Sub CommandButton1_Click()
    Dim mycontrol As Control
   on error resume next

多谢了,正是我想要,顺便更多问一下,如果是下图这种情况,我想把两个按钮都显示出来行不行? 快照1.jpg
回复

使用道具 举报

发表于 2012-10-18 12:48 | 显示全部楼层
1)两个按钮都显示出,是什么结果,能比如下么

2)请问extyg,5#可以不要on error那句了吧?
回复

使用道具 举报

 楼主| 发表于 2012-10-18 12:52 | 显示全部楼层
爱疯 发表于 2012-10-18 12:48
1)两个按钮都显示出,是什么结果,能比如下么

2)请问extyg,5#可以不要on error那句了吧?

就象我图中选了两个:分别是1 和 三
我点确定后,两次msgbox,第一次显示 1 ,第二次显示 三
回复

使用道具 举报

发表于 2012-10-18 13:04 | 显示全部楼层
能传下你变了后的附件么?

frame2里只1个控件,不知为什么你这么做啊?
回复

使用道具 举报

 楼主| 发表于 2012-10-18 13:07 | 显示全部楼层
爱疯 发表于 2012-10-18 13:04
能传下你变了后的附件么?

frame2里只1个控件,不知为什么你这么做啊?

示例.zip (8.31 KB, 下载次数: 38)
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-3-29 13:12 , Processed in 0.873421 second(s), 12 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表