2011-11-25 171 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

相關問題