Board logo

標題: [發問] 如何讓表單物件對應到物件類別內呢? [打印本頁]

作者: dechiuan999    時間: 2015-5-15 14:24     標題: 如何讓表單物件對應到物件類別內呢?

各位大大好:
[attach]20947[/attach]
  小弟對物件類別很著迷,
但在學習過程一直碰壁。
現小弟摸擬一問題如下
一、新增表單內含TEXTBOX1
及COMMANDBUTTON1
Option Explicit
Dim mycls1 As mClass1
Private Sub CommandButton1_Click()
    With mycls1
        .test2 mycls1     '由此可執行,而改由在 MCLASS1的MCMD1_CLASS會出現ERROR
    End With
End Sub

Private Sub UserForm_Initialize()   
    Set mycls1 = New mClass1
    With mycls1
        Set .Txt1 = Me.Controls("TextBox1")
        Set .Cmd1 = Me.Controls("CommandButton1")
        .mTxt1 = "test"
    End With
End Sub

二、新增二個物件類別

--- MCLASS1 ---

Option Explicit

Public myCls2 As mClass2
Public WithEvents mTxt1 As MSForms.TextBox
Public WithEvents mCmd1 As MSForms.CommandButton

Public Property Set Txt1(setTxt1 As MSForms.TextBox)
    Set mTxt1 = setTxt1
End Property
Public Property Set Cmd1(setCmd1 As MSForms.CommandButton)
    Set mCmd1 = setCmd1
End Property

Private Sub Class_Initialize()
    Set myCls2 = New mClass2
End Sub
Private Sub mCmd1_Click()   
    'myCls2.mTest mycls1
    test2 mClass1     '二種方式會出現執行階段錯誤'424' 此處須要物件
   
End Sub
Function test2(ByVal mycls1 As mClass1)
    myCls2.mTest mycls1
End Function

--- MCLASS2  ---

Option Explicit

Sub mTest(ByVal mycls1 As mClass1)
    Dim mStr As String   
    With mycls1
        mStr = .mTxt1
    End With
End Sub

請問應如何修改在MCLASS1的MCMD1_CLICK增設MCLS1物件呢?
感恩各位大大!
作者: stillfish00    時間: 2015-5-15 17:39

回復 1# dechiuan999
物件類別中,要參考到自己本身這個物件要用Me
所以你應該要改為 test2 Me

就像你在UserForm的程式碼中,你要知道UserForm的name可以用Me.Nameㄧ樣意思
作者: dechiuan999    時間: 2015-5-15 17:50

回復 2# stillfish00


    感恩大大!
又讓小弟跨出一大步。

就感恩。
作者: GBKEE    時間: 2015-5-20 05:51

回復 3# dechiuan999
表單模組中可直接指定這表單控制項物件
  1. Private Sub UserForm_Initialize()   
  2.     Set mycls1 = New mClass1
  3.     With mycls1
  4.         Set .Txt1 = TextBox1
  5.         Set .Cmd1 =CommandButton1
  6.      '   Set .Txt1 = Me.Controls("TextBox1")
  7.       '  Set .Cmd1 = Me.Controls("CommandButton1")
  8.         .mTxt1 = "test"
  9.     End With
  10. End Sub
複製代碼





歡迎光臨 麻辣家族討論版版 (http://forum.twbts.com/)