Excel VBA – 工作表属性不会像它应该分配一个字段

新的VBA – 试图使用工作表属性,就像我会在OOP语言中使用Getters和Setters。 我在Sheet1中有以下代码(为了清晰起见而简化):

Option Explicit Private bAllowChange As Boolean Public Property Let AllowChange(bLetAllowChange As Boolean) bAllowChange = bLetAllowChange End Property 

我期望当AllowChange属性由另一个模块中的一个子项调用时, bAllowChange字段将相应地更新。 通过使用VBE的debuggingfunction,我可以看到AllowChange正在传递正确的值( bLetAllowChange采用正确的值),但行

 bAllowChange = bLetAllowChange 

不会将值bAllowChange 。 如果我将bAllowChange设置为Public,那么它按预期工作,但这首先破坏了使用Properties的目的。 这可能是简单的,我不了解VBA的范围。 有什么build议么? 提前致谢。

以下为我工作:

在Module1中:

 Option Explicit Sub SetItToFalse() Sheet1.AllowChange = False End Sub Sub SetItToTrue() Sheet1.AllowChange = True End Sub 

在代码名称为Sheet1的工作表Sheet1

 Option Explicit Private bAllowChange As Boolean Public Property Let AllowChange(bLetAllowChange As Boolean) bAllowChange = bLetAllowChange End Property Private Sub Worksheet_SelectionChange(ByVal Target As Range) MsgBox bAllowChange End Sub 

随着代码设置,我可以调用SetItToFalse子程序,然后每个select更改显示我这是False 。 调用SetItToTrue每次select更改都会显示为“ True

如果你想持久性属性,试试这个(只是一个如何设置/获取/更新/删除自定义属性的例子)

 Sub customProperties() ActiveWorkbook.Sheets("Sheet1").customProperties.Add "abc123", 123 Debug.Print ActiveWorkbook.Sheets("Sheet1").customProperties(1) ' custom properties are not indexed by name ActiveWorkbook.Sheets("Sheet1").customProperties(1).Value = "this is my data" Debug.Print ActiveWorkbook.Sheets("Sheet1").customProperties(1) ActiveWorkbook.Sheets("Sheet1").customProperties(1).Delete ' CustomDocumentProperties Types ' msoPropertyTypeBoolean 2 ' msoPropertyTypeDate 3 ' msoPropertyTypeFloat 5 ' msoPropertyTypeNumber 1 ' msoPropertyTypeString 4 ActiveWorkbook.CustomDocumentProperties.Add Name:="xyz", LinkToContent:=False, Type:=msoPropertyTypeString, Value:="xyz" Debug.Print ActiveWorkbook.CustomDocumentProperties("xyz") ActiveWorkbook.CustomDocumentProperties("xyz").Value = "abcdefg" Debug.Print ActiveWorkbook.CustomDocumentProperties("xyz") ActiveWorkbook.CustomDocumentProperties("xyz").Delete End Sub 

您可以使用工作表的名称集合永久存储您的自定义工作表属性值。

主要的警告是这个值返回前面加一个等号。 (例如,在设置name.Value = True ,name.Value会= =True )。 我在我的例子中为此做了一个解决方法。

在这里输入图像说明


 Public Property Let AllowChange(bLetAllowChange As Boolean) Dim n As Name On Error Resume Next Set n = Me.Names("bLetAllowChange") If n Is Nothing Then Set n = Me.Names.Add("bLetAllowChange", bLetAllowChange) End If n.Value = bLetAllowChange On Error GoTo 0 End Property Public Property Get AllowChange() As Boolean Dim result As String On Error Resume Next result = Me.Names("bLetAllowChange").Value result = Right(result, Len(result) - 1) AllowChange = Application.Evaluate(result) On Error GoTo 0 End Property