2014-05-21 65 views
2

在VBA for Excel 2007中,我想將文本框添加到活動工作表並將其公式設置爲單元格。我的問題是AddTextbox函數返回一個類型名爲Shape而不是TextBox的對象,因此它沒有Formula屬性來設置。相反,我最終遍歷所有文本框以找到正確的文本框,然後設置其Formula。有一個更好的方法嗎?插入文本框並設置公式

Sub insertTextBoxWithFormula() 
    Set newTextBox = ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 200, 200, 150, 150) 
    newTextBox.Name = "New TextBox" 
    'newTextBox.Formula = "=$A$1" 'This is what I wanted to do 

    'This is what I did instead 
    For Each CurrentTextBox In ActiveSheet.TextBoxes 
     If CurrentTextBox.Name = "New TextBox" Then 
      CurrentTextBox.Formula = "=B3" 
      CurrentTextBox.Name = "Finished TextBox" 
     End If 
    Next CurrentTextBox 
End Sub 

回答

1

您可以使用控件的名稱爲TextBoxes集合建立索引。所以,你的例子可以簡寫爲:

ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 200, 200, 150, 150).Name = "New TextBox" 
ActiveSheet.TextBoxes("New TextBox").Formula = "=$B$3" 
2

或者這樣:

Dim newshp As Shape 
Dim newtb As TextBox 

Set newshp = ActiveSheet.Shapes.AddTextbox _ 
    (msoTextOrientationHorizontal, 200, 200, 150, 150) 
Set newtb = newshp.OLEFormat.Object 
newtb.Formula = "$A$1"