2017-04-11 47 views
1

您好我有一個複選框和代碼,如果我運行它顯示錯誤。請糾正這個錯誤。如何將屬性分配給複選框

Private Sub CheckBox1_Click() 
    With Sheets("bom") 
     If .CheckBox1.Value = True Then 
      .Range("show_all_level") = "Yes" 
     Else 
      .Range("show_all_level") = "No" 
     End If 
    End With 
End Sub 

類型的錯誤:

enter image description here

+1

您可能沒有定義的名爲「show_all_level」的範圍。檢查你的公式選項卡>名稱管理器,看看你是否有一個名爲「show_all_level」的定義範圍? –

+1

是否在複選框的同一工作表上定義了命名範圍** show_all_level **?即工作表(「bom」) – Jeeped

+0

更重要的是Sheet bom上的CheckBox1? – sktneer

回答

1

嘗試下面的代碼,它應該處理你可能有你的 「show_all_level」 Name Range不同的方案。

Option Explicit 

Private Sub CheckBox1_Click() 

Dim Nm   As Name 
Dim NmExist  As Boolean 
Dim NameRng  As Range 

' loop through all Name Ranges in ThisWorkbook 
For Each Nm In ThisWorkbook.Names 
    If Nm.Parent.Name Like "bom" Then '<-- check if name range parent (Sheet.Name) is "bom" 
     MsgBox Nm.Name & " Name Range exists is sheet " & Chr(34) & Nm.Parent.Name & Chr(34) 
     NmExist = True ' raise the flag >> Name exist in "bom" sheet 
     Set NameRng = Nm.RefersToRange ' set the Range to the Name Range 
     Exit For 
    ElseIf Nm.Parent.CodeName Like "ThisWorkbook" Then '<-- check if name scope is "ThisWorkbook" 
     MsgBox Nm.Name & " Name Range exists as WorkBook scope" 
     NmExist = True ' raise the flag >> Name exist in Workbook scope 
     Set NameRng = Nm.RefersToRange ' set the Range to the Name Range 
     Exit For 
    End If 
Next Nm 

' verify that "show_all_level" name exist in "bom" sheet (or Workbook scope) 
If Not NmExist Then 
    MsgBox Chr(34) & "show_all_level" & Chr(34) & "Name Range, doesn't exist in the desired sheet", vbCritical 
    Exit Sub 
End If 

With Sheets("bom") 
    If .CheckBox1.Value = True Then 
     NameRng.Value = "Yes" 
    Else 
     NameRng.Value = "No" 
    End If 
End With 

End Sub 
+0

@DINESHKUMARPALANISAMY見https://meta.stackexchange.com/a/5235/289619 – 0m3r

+1

@ 0m3r感謝您的這個鏈接;)我在過去需要它很多次;) –

+0

提醒他們SO社區如何工作的好方法:-) – 0m3r

相關問題