2015-06-15 34 views
0

我想將文本框添加到預先存在的用戶表單中,並且還要更改VBA Excel 2010中用戶表單的高度。我希望添加文本框並更改高度在設計時,但我需要使用代碼。以下代碼是我迄今爲止的內容。以編程方式向現有用戶表單添加文本時出錯

Sub Practice() 
Dim hght As Single 
Dim NameUserForm As String 
Dim MyUserForm As Object 

'Name of userform 
NameUserForm = "test" 

Set MyUserForm = ThisWorkbook.VBProject _ 
.VBComponents(NameUserForm) 

hght = MyUserForm.Properties("Height") 

With MyUserForm 

    .Properties("Height") = hght + 25 

End With 

Set NewTextBox = MyUserForm.Designer.Controls.Add("Forms.TextBox.1") 

    With NewTextBox 
     .TextAlign = fmTextAlignCenter 
     .Width = 66 
     .Height = 18 
     .Left = 40 
     .Top = hght 
    End With 
test.Show 

End Sub 

我得到一個錯誤的下面一行

Set NewTextBox = MyUserForm.Designer.Controls.Add("Forms.TextBox.1") 

和錯誤讀作:

運行時錯誤 '-2147319767(80028029)' 向前無效引用,或引用未編譯的類型。

我不知道我在做什麼錯。我也問及mrexcel.com同樣的問題,這裏是在那一個http://www.mrexcel.com/forum/excel-questions/861582-use-visual-basic-applications-add-textbox-existing-userform.html

+0

你說「高度在設計時改變了」。你的意思是「設計時間」還是「運行時間」?你試圖展示這個表格,所以我猜你的意思是後者。 – ChipsLetten

+0

對不起,我是vba的新手。我希望一切都在設計時完成,所以它是永久的。 –

回答

0

如果你想改變一個窗體的屬性代碼的一部分,將Show形式,您要更改鏈接運行。我認爲你的代碼正在混合改變已保存的表單設計的設計,並對當前的表單實例進行更改。

下面的代碼將用戶窗體作爲對象進行處理。新的文本框被添加到表單的臨時實例。

Sub Practice() 
Dim hght As Single 
Dim MyUserForm As testUserForm 
Dim NewTextBox As Control 

    Set MyUserForm = New testUserForm 

    hght = MyUserForm.Height 

    With MyUserForm 

     .Height = hght + 25 

    End With 

    Set NewTextBox = MyUserForm.Controls.Add("Forms.TextBox.1") 

    With NewTextBox 
     .TextAlign = fmTextAlignCenter 
     .Width = 66 
     .Height = 18 
     .Left = 40 
     .Top = hght 
    End With 
    MyUserForm.Show 

    ' Do something with the form, user clicks Ok or close button 
    Set MyUserForm = Nothing 
End Sub 
+0

感謝您花時間瀏覽我的代碼並回復。你提到「新的文本框被添加到表單的臨時實例。」需要對代碼進行哪些更改才能對用戶窗體進行永久更改。再次需要用代碼進行更改。在設計視圖中進行更改並不是我要找的。 –

0

那麼我有一些工作。我不確定我做了什麼修正了它,但在這裏是爲了任何其他人在同樣的事情上掙扎。 (注意:我對變量名稱做了一些修改)

Sub DesignTimeTxtBox() 

Dim txtBox As Variant 
Dim NameUserForm As String 
Dim hght As Single 

NameUserForm = "test" 

Set MyUserForm = ThisWorkbook.VBProject _ 
    .VBComponents(NameUserForm) 

hght = MyUserForm.Properties("Height") + 25 
MyUserForm.Properties("Height") = hght 

Set txtBox = ThisWorkbook.VBProject.VBComponents(NameUserForm).Designer.Controls.Add("Forms.TextBox.1") 
With txtBox 
    .Width = 66 
    .Top = 133 
    .Left = 42 
End With 
End Sub 
相關問題