【发布时间】:2017-07-13 11:46:12
【问题描述】:
我需要以下代码方面的帮助。
它的第一个目的是检查按钮是否存在(工作正常)。
在电子表格上创建一个动态按钮(“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
【问题讨论】:
标签: excel vba button dynamic module