Excel VBA类属性返回公共长变量,但不返回公共字符串变量

时间:2014-06-11 15:49:35

标签: oop excel-vba vba excel

这是我第一次以面向对象的方式经历:希望如此有助于我的。 (并且发现了这一点,这看起来很有帮助,但我仍然没有看到它:Excel Class properties returning empty strings

首先:我想要什么?用于导入表并具有对其中的某些列进行排序和过滤(以及更多操作)的方法的类。列的位置(如果不是名称)可能会不时变化。

第二:我的班级:(摘录)     选项明确

Private ColNumber_ As Long
Private ColTxt_ As String
Private blnVis As Boolean
Private blnSort As Boolean
Private sCrit As String

Private Sub Class_Initialize()
   blnVis = True
   blnSort = False
   ColTxt_ = ""
End Sub

Public Sub initCols(ColTxt_ As String)
   Dim rng As Range
   ActiveWorkbook.Worksheets("Glasliste").Range("Tabelle1[#Headers]").Select
   Set rng = Selection.Find(What:=ColTxt_, LookIn:=xlFormulas, _
     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
     MatchCase:=False, SearchFormat:=False) 'After:=ActiveCell,
   MsgBox rng.Text ' This gives me the desired text, however I cannot use it outside of the class
   MsgBox rng.Column
   ColNumber_ = rng.Column
   ColTxt_ = rng.Text
End Sub

'Get the text of the header
Public Property Get ColTxt() As String 'Optional lngOrder As Long
   ColTxt = ColTxt_
End Property

'Get the position of the Column
Public Property Get ColNumber() As Long 'Optional lngOrder As Long
   ColNumber = ColNumber_
End Property

第三:这是我的代码(摘录):

Sub initSpalten()
   Dim Typ As clsSpalte: Set Typ = New clsSpalte: Typ.initCols ("Typ")
   MsgBox Typ.ColTxt ' Here I get an empty string
   Dim Aufbau As clsSpalte: Set Aufbau = New clsSpalte: Aufbau.initCols ("Aufbau")
   MsgBox Aufbau.ColNumber ' I here get the right number... but dont see any difference?
End Sub
第四:我的问题,或者我不明白的问题: 使用上面的MsgBox,评论"在这里我得到一个空字符串"我的代码以后不会工作。我确实需要这个文字。我无法直接分配相应的私有变量。但是,为什么它适用于长期" Aufbau.ColNumber" ? 对你们中的某些人来说,这不是一个谜吗? (希望)...非常感谢任何帮助! 托马斯

1 个答案:

答案 0 :(得分:1)

您的ColTxt_变量是"重影"具有相同名称的类成员变量。尝试更改:

'                   vvv
Public Sub initCols(txt As String)
   Dim rng As Range
   ActiveWorkbook.Worksheets("Glasliste").Range("Tabelle1[#Headers]").Select
'                                 vvv 
   Set rng = Selection.Find(What:=txt, LookIn:=xlFormulas, _
     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
     MatchCase:=False, SearchFormat:=False) 'After:=ActiveCell,
   MsgBox rng.Text ' This gives me the desired text, however I cannot use it outside of the class
   MsgBox rng.Column
   ColNumber_ = rng.Column
   ColTxt_ = rng.Text
End Sub