VBA类模块作为工作表

时间:2018-04-15 21:59:02

标签: vba oop

请考虑以下"代码":

Sub MySub()
  Dim MySheet As Worksheet
  Set MySheet = ActiveSheet
  MySheet.DeleteAllRedWords 'This is a Sub
  MsgBox MySheet.NumberOfChangesThisWeek 'This is a function
  MySheet.ActiveOwner = "Sam" 'This is a property
End Sub

这可能吗?类模块可以解决这个问题吗?我尝试了下面的代码,但是我收到错误438(对象不支持此属性或方法)。有可能吗?

'CLASS MODULE CODE: MyWorkingSheet Class
Private Sub class_initialize()
  Me = ActiveSheet
End Sub

'NORMAL MODULE CODE
Sub MySub()
  Dim MyTodaySheet As MyWorkingSheet
  Set MyTodaySheet = New MyWorkingSheet
End Sub

1 个答案:

答案 0 :(得分:1)

Sub MySub()

  Dim MySheet As New MyWorkingSheet

  Set MySheet.Sheet = ActiveSheet

  MySheet.DeleteAllRedWords

  'etc

End Sub

类别:

'CLASS MODULE CODE: MyWorkingSheet Class
Private m_sht As WorkSheet

'set a reference to the worksheet you want to "wrap" with your class
Property Set Sheet(sht As WorkSheet)
    Set m_sht = sht
End Property

Sub DeleteAllRedWords()
    'in all your class methods reference m_sht
    With m_sht.UsedRange
        'code to delete all red words
    End With
End Sub

'other methods/functions