0
我需要以下代碼的一些幫助。VBA在excel中創建動態按鈕
它的第一個目的是檢查按鈕是否存在(工作正常)。
創建動態按鈕,電子表格( 「Top20LossContracts」),(這個工程太)
最後,當按鈕被按下它運行另一個名爲 「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
謝謝Domenic!它現在有效,正如你所說我提到了錯誤的財產。 – Patrick