how to link a checkbox on Excel to a VBA code

2019-08-28 18:28发布

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?

3条回答
干净又极端
2楼-- · 2019-08-28 18:58

Should it not be

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

?

查看更多
The star\"
3楼-- · 2019-08-28 19:01

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
查看更多
淡お忘
4楼-- · 2019-08-28 19:15

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.

VBAProject tree

查看更多
登录 后发表回答