2017-07-13 299 views
0

我需要以下代碼的一些幫助。VBA在excel中創建動態按鈕

  1. 它的第一個目的是檢查按鈕是否存在(工作正常)。

  2. 創建動態按鈕,電子表格( 「Top20LossContracts」),(這個工程太)

  3. 最後,當按鈕被按下它運行另一個名爲 「FilterPivotTable」

子方法

上面的第3點在「Sub Modify_CommButton」中有一個編譯錯誤,並且不會創建所需的代碼模塊。我不知道如何繼續。

即使我厭倦了聲明所有數據類型,也會出現諸如「找不到方法或數據成員」之類的錯誤。

在Excel 2013上運行代碼 非常感謝。

Option Explicit 

    ' Sub works fine 
    Sub AddComm_button() 
     Dim obj As OLEObject 
     Dim FindButton As Boolean 
     Dim mybutton 
     For Each obj In ActiveSheet.OLEObjects 
      If TypeOf obj.Object Is MSForms.CommandButton Then 
     If obj.Name = "Filter_profit" Then 
      FindButton = True 
      Exit For 
     End If 
     End If 
    Next 

    If Not FindButton Then 
     Set mybutton = ActiveSheet.OLEObjects.Add   (ClassType:="Forms.CommandButton.1") 
     Application.DisplayAlerts = False 
     With mybutton 
     .Name = "Filter_profit"  
     .Object.Caption = "Filter Profit" 
     .Top = 20 
     .Left = 126 
     .Width = 126.75 
     .Height = 25.5 
     .Placement = xlMoveAndSize 
     .PrintObject = True   
     End With 

     Call Modify_CommButton 
    End If 
    End Sub 

    Sub Modify_CommButton() 
    Dim LineNum As Long 'Line number in module 
    Dim SubName As String 'Event to change as text 
    Dim Proc As String 'Procedure string 
    Dim EndS As String 'End sub string 
    Dim Ap As String 'Apostrophe 
    Dim Tabs As String 'Tab 
    Dim LF As String 'Line feed or carriage return 
    Dim ws As Worksheet 

    Ap = Chr(34) 
    Tabs = Chr(9) 
    LF = Chr(13) 
    EndS = "End Sub" 
    SubName = "Private Sub Filter_profit_Click()" & LF 
    Proc = Tabs & "Call " & Ap & "FilterPivotTable(0)" & Ap & LF 
    Proc = Proc & "End Sub" & LF 
    ws = Sheets("Top20LossContracts") 

    Application.DisplayAlerts = False 
    Set NewModule = ws.VBProject.VBComponents("Top20LossContracts").CodeModule 
    With NewModule 
    LineNum = .CountOfLines + 1 
    .InsertLines LineNum, SubName & Proc & EndS 
    End With 
    End Sub 

回答

0

VBProject是Workbook對象的屬性,而不是Worksheet對象的屬性。此外,在引用VBComponents集合中的組件時,您需要使用工作表的代碼名稱,而不是表單名稱。

Set NewModule = ActiveWorkbook.VBProject.VBComponents(ws.CodeName).CodeModule 

另外,您爲過程構建的字符串不太正確。而且,可以使用VBA常量而不是將字符(如製表符或回車符)分配給變量。我認爲你的程序可以改寫如下...

Sub Modify_CommButton() 
    Dim ws As Worksheet 
    Dim CM As Object 'Code module 
    Dim LineNum As Long 'Line number 
    Dim Proc As String 'Procedure 

    Set ws = Worksheets("Top20LossContracts") 

    Proc = "Private Sub Filter_profit_Click()" & vbCrLf 
    Proc = Proc & vbTab & "Call FilterPivotTable(0)" & vbCrLf 
    Proc = Proc & "End Sub" & vbCrLf 

    Application.DisplayAlerts = False 
    Set CM = ActiveWorkbook.VBProject.VBComponents(ws.CodeName).CodeModule 
    With CM 
     LineNum = .CountOfLines + 1 
    .InsertLines LineNum, Proc 
    End With 
End Sub 
+0

謝謝Domenic!它現在有效,正如你所說我提到了錯誤的財產。 – Patrick