2014-12-26 101 views
0

我在Excel中使用表單按鈕, 當我添加表單按鈕時,他們被添加名稱Button 1, Button 2, Button 3 ...... 一旦我清除表單並刪除所有按鈕,當我再次添加它們時,我想要創建Button 1而不是Button 4。 這可能嗎?如果是的話如何實現呢? 在此先感謝刪除表單按鈕1後應創建表單按鈕1

代碼我用來創建按鈕

ActiveSheet.Buttons.Add(_ 
    ActiveCell.Left, _ 
    ActiveCell.Top, _ 
    ActiveCell.Offset(0, 1).Range("A1:C2").Width, _ 
    ActiveCell.Offset(0, 1).Range("A1:A3").Height) 

回答

0

如果您使用此,它會給你一些功能集成到更動態命名的按鈕。但是,由於您正在使用ActiveCell來放置它,所以如果您嘗試一次創建它們,則會導致它們的所有重疊問題。如果你能詳細說明按鈕放置的位置,如果它們相同,或者決定了它們的位置,我可以給出更多細節。

Dim lCount As Long 

lCount = 1 

Set newButton = ActiveSheet.Buttons.Add(_ 
    ActiveCell.Left, _ 
    ActiveCell.Top, _ 
    ActiveCell.Offset(0, 1).Range("A1:C2").Width, _ 
    ActiveCell.Offset(0, 1).Range("A1:A3").Height) 
With newButton 
    .Name = "Button" & lCount 'The actual button name. 
    .Caption = newButton.Name 'This is the DISPLAY on the button. 
End With 

另一種方法是省略lCount並只在代碼中命名按鈕。這將涉及到激活所需的單元,然後運行代碼,並將.Name屬性中的值從1更改爲2,3等。

With newButton 
    .Name = "Button1"   'The actual button name. 
    .Caption = newButton.Name 'This is the DISPLAY on the button. 
End With 

你可以有一個隱藏的工作表(例如,在「HiddenHelper」),其跟蹤的您已經創建多少按鍵,並有lCount指的是電池。當您清除表,您重置價值,以及回到1。然後,當你添加一個按鈕,都將代碼添加至單元格值保持跟蹤你有多少這樣使用:

Dim lCount As Long 

lCount = Sheets("HiddenHelper").Range("A1") 

Set newButton = ActiveSheet.Buttons.Add(_ 
    ActiveCell.Left, _ 
    ActiveCell.Top, _ 
    ActiveCell.Offset(0, 1).Range("A1:C2").Width, _ 
    ActiveCell.Offset(0, 1).Range("A1:A3").Height) 
With newButton 
    .Name = "Button" & lCount 'The actual button name. 
    .Caption = newButton.Name 'This is the DISPLAY on the button. 
End With 

Sheets("HiddenHelper").Range("A1") = Sheets("HiddenHelper").Range("A1") + 1 

當然,您可以隨心所欲地命名助手錶,並將按鈕數的範圍設置爲適合您的任何範圍。