2017-08-21 27 views
0

我想在Excel中創建一個工具。我的第一個問題是我無法可靠地實例化我的工作表上的標籤和文本框。我目前有下面的代碼。使用vba在工作表中實例化ActiveX控件

Sub Test2() 
Dim Schedule As Worksheet 
Set Schedule = Worksheets("Schedule") 

'Creates the row number 
Schedule.OLEObjects.Add ClassType:="Forms.Label.1" 
With Worksheets("Schedule").Label1 
.Caption = 1 
.width = 18 
.Height = 18 
.Top = 0 
.Left = 0 
.SpecialEffect = 1 
.BackColor = &H8000000F 
.TextAlign = 2 
End With 

End Sub 

Sub Test3() 
Dim Schedule As Worksheet 
Set Schedule = Worksheets("Schedule") 

Schedule.OLEObjects.Add ClassType:="Forms.TextBox.1" 

With Worksheets("Schedule").TextBox1 
.Text = "Task Name" 
.width = 200 
.Height = 18 
.Top = 0 
.Left = 18 
.SpecialEffect = 0 
.BackColor = &H80000005 
.TextAlign = 1 
.BorderStyle = 1 
End With 

End Sub 

自己的這些都工作,但是當你運行一個接着另一個產生錯誤

「運行時錯誤‘438’:對象不支持此屬性或方法「。

有什麼建議嗎?

此外,如果我創建了無限量的數據,我將如何存儲和訪問這些標籤和文本框,我會採取某種收集方式?

+0

錯誤發生在哪一行? –

回答

0

對於某些屬性,你需要參考OleoObject對象的對象屬性...

Sub Test2() 

    'Creates the row number 
    With Worksheets("Schedule").OLEObjects.Add(ClassType:="Forms.Label.1") 
     .Left = 0 
     .Top = 0 
     .Width = 18 
     .Height = 18 
     With .Object 
      .Caption = 1 
      .SpecialEffect = 1 
      .BackColor = &H8000000F 
      .TextAlign = 2 
     End With 
    End With 

End Sub 

Sub Test3() 

    With Worksheets("Schedule").OLEObjects.Add(ClassType:="Forms.TextBox.1") 
     .Left = 18 
     .Top = 0 
     .Width = 200 
     .Height = 18 
     With .Object 
      .Text = "Task Name" 
      .SpecialEffect = 0 
      .BackColor = &H80000005 
      .TextAlign = 1 
      .BorderStyle = 1 
     End With 
    End With 

End Sub 

希望這有助於!

相關問題