2011-11-25 128 views
0

基本上,我是一名VBA程序员,Iam面临VBA复选框控件的严重问题。我必须根据用户选择选择和取消选中复选框。我相信这也是vb.net的一个普遍问题。无法解决复选框的选择和取消选择

一些示例代码

sub chk3_Click() 

    if userform.chk3.value = true then 
    userform.chk4.value = true 
    userform.chk2.value = true 
    end if 

end sub 

sub chk4_click() 

    if userform.chk4.value = true then 
    userform.chk3.value=true 
    userform.chk1.value=true 
    end if 

end sub  

这是示例代码,我具有基于checkboxes.but问题林面对的是用户选择打开其他复选框,当执行语句

userform.chk4.value = true in the sub chk3_click 

正在调用子chk4_click子,并再次找到

userform.chk3.value=true in sub chk4_click(), invoking the sub chk3_click 

我无法理解如何解决它。

我已经尝试过各种事件mousedown,mouseup和更新后的值也更新但没有working.These事件崩溃的工具我不明白为什么,但他们崩溃,所以我只是忽略使用这些事件。

最后,我用了一个在工作簿中全局定义的标志,并且使用if条件来完成它,但它看起来很糟糕的编码风格。任何人都可以帮助我吗?

这是我为解决问题所做的。它的工作原理,但我不认为它的编程风格。

dim i as integer 

sub ch3_click() 

    if i = 0 then 
    i = 1 
    if userform.chk3.value=true then 
     userform.chk4.value =true 
     userform.chk2.value=true 
    end if 
    i = 0 
    end if 

end sub 

sub chk4_click 

    if i = 0 then 
    i = 1 
    if userform.chk4.value = true then 
     userform.chk3.value=true 
     userform.chk1.value=true 
    end if 
    i = 0 
    end if 

end sub 

任何帮助非常感谢。

回答

1

这实际上是解决这个问题一个非常有效的方法,你只需要对我更具描述性的名称和类型,如

Dim InClickEvent As Boolean 

然后改变你的点击事件的代码是这样的:

if Not InClickEvent then 
    InClickEvent = True 
    if userform.chk3.value=true then 
     userform.chk4.value =true 
     userform.chk2.value=true 
    end if 
    InClickEvent = False 
    end if 

更妙的是,如果你的VBA的版本支持的try /最后,我认为是这样,你可以确保该标志始终清零,即使你有以下版本的代码错误:

if Not InClickEvent then 
    Try 
     InClickEvent = True 
     if userform.chk3.value=true then 
      userform.chk4.value =true 
      userform.chk2.value=true 
     end if 
    Finally 
     InClickEvent = False 
    End Try 
    end if 
0

看看Application.EnableEvents

sub chk3_Click() 
    Application.EnableEvents =false 
    if userform.chk3.value = true then 
    userform.chk4.value = true 
    userform.chk2.value = true 
    end if 
    Application.EnableEvents =true 
end sub 

sub chk4_click() 
    Application.EnableEvents =false 
    if userform.chk4.value = true then 
    userform.chk3.value=true 
    userform.chk1.value=true 
    end if 
    Application.EnableEvents =true 
end sub 
+0

对不起它AINT工作 – niko

相关问题