Excel将Item设置为类属性Get和Let的默认值

hfyxw5xn  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(155)

我创建了这个类来进行实验。我的目标是看看我是否可以以这种格式读取/写入数据:

x = AppInventory(r,c): AppInventory(r,c) = x
x = AppInventory("A1"): AppInventory("A1") = x
x = AppInventory(cellRange): AppInventory(cell(cellRange) = x

字符串
这在添加.Item: x = AppInventory.Item(r,c)时有效
但我希望消除.Item(),这是可能的默认为。项目?
有没有人默认了Item,这样你就不用输入了?或者有其他更简单的方法吗?我试着在主代码中使用Get/Let和Property,这不起作用,因为r,c vs字符串文本证明是一个问题,因为有时我使用1个参数,有时2个。
任何想法都很感激。谢谢。
类名:AppInventory

Private ws As Worksheet
    Private targetCell As Range
        
    Private Sub Class_Initialize()
        Set ws = ThisWorkbook.Worksheets("AppInventory")
    End Sub
    
    Public Property Get Item(Index1 As Variant, Optional Index2 As Variant) As Variant
        Set targetCell = GetTargetCell(Index1, Index2)
        Item = targetCell.Value
    End Property
        
    Public Property Let Item(Index1 As Variant, Optional Index2 As Variant, ByVal Value As Variant)
        Set targetCell = GetTargetCell(Index1, Index2)
        targetCell.Value = Value
    End Property
        
    Private Function GetTargetCell(Index1 As Variant, Optional Index2 As Variant) As Range
        Select Case VarType(Index1)
            Case vbInteger, vbLong ' Numeric, likely row number
                Set GetTargetCell = ws.Cells(Index1, Index2)
            Case vbString ' String, like "A1"
                Set GetTargetCell = ws.Range(Index1)
            Case vbObject ' Range object
                Set GetTargetCell = ws.Range(Index1.Address)
            Case Else
                MsgBox "Invalid input"
        End Select
    End Function


我的想法失败了:

Public Default Property Get Item(Index1 As Variant, Optional Index2 As Variant) As Variant
Default Public Property Get Item(Index1 As Variant, Optional Index2 As Variant) As Variant


我甚至尝试导出类并在Get Item()之后添加Attribute Item.VB UserMemID = 0,然后再将其导入回来看看是否有效。我想我曾经让它工作过一次,但当我用简单的注解修改类时,我认为它消失了,我不能让它再次工作。

tkqqtvp1

tkqqtvp11#

您所提供的程式码看起来好像不是在建立类别的执行严修。

x = AppInventory(r,c): AppInventory(r,c) = x
x = AppInventory("A1"): AppInventory("A1") = x
x = AppInventory(cellRng): AppInventory(cell(rnd) = x

字符串
除非将AppInventory设置为PredeclaredId,否则上面的代码将不起作用。
尝试以下

Dim MyInv as AppInventory
Set myInv = new AppInventory
myInv.Item(r,c)=x


如果将Item设置为默认成员,则可以消除.Item。
许多类别属性无法从VBA中取得,这表示您必须汇出程式码、设定属性,然后再重新汇入。
一个更简单的方法是安装免费的VBA的Rubberduck插件。这个插件允许你通过使用前缀为“@”的注解来设置属性

'\@DefaultMember
Public Property Get Item(Index1 As Variant, Optional Index2 As Variant) As Variant
        Set targetCell = GetTargetCell(Index1, Index2)
        Item = targetCell.Value
    End Property
        
    Public Property Let Item(Index1 As Variant, Optional Index2 As Variant, ByVal Value As Variant)
        Set targetCell = GetTargetCell(Index1, Index2)
        targetCell.Value = Value
    End Property


您需要运行Rubberduck解析来更新属性。
好运

相关问题