how to link a checkbox on Excel to a VBA code

混江龙づ霸主 提交于 2019-12-13 02:51:20

问题


I have created a checkbox on my Excel Work sheet, using design mode I have leftclicked it and named it ChkV, and I wrote a VBA code but when I run it I get an message telling that the variable is not defined.

    If ChkV.Value = True Then
        ' my code
    End If

Did I not label the check box correctly, what am I doing wrong ? How should I fix the mistake?


回答1:


Should it not be

If  activesheet.Checkboxes("ChkV") = xlOn Then
'your code
End If

?




回答2:


You have this error when you call your code outside Sheet module where your checkbox is located. To improve your code you need to add references to sheet where checkbox belongs to, like:

If Sheets("Sheet 1").ChkV.Value = True Then
    ' my code
End If



回答3:


Hi i was breaking my head over and over again for this, but searching i found that you need to refer by the CodeName's sheet or using OleObjects

  1. By Code Name is how you see in the VBA Project tree:

    Hoja1.[CheckBoxName].Value  
    '' In English or what ever you may call your sheet is:
    Sheet1.[CheckBoxName].Value
    
  2. By OleObjects is:

    Dim Wks as Worksheet  
    Set Wks = Worksheets("[SheetName]")    '' in this case "Prueba"
    Wks.OLEObjects("[CheckBoxName]").Object.Value
    

Note that my Excel is in Spanish thats why you see Hoja1, in English is Sheet1 and you can find something else here.



来源:https://stackoverflow.com/questions/17237296/how-to-link-a-checkbox-on-excel-to-a-vba-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!