主要代码的一部分与图表表格相关,该图表表格允许点击图表(编码在图表表格中完成)触发宏。但主要程序涉及删除和创建图表。程序删除图表工作表后,图表工作表中的代码也会被删除。如何在创建新图表时执行图表工作表代码?
Sub AddNewChart()
Dim Newchart As Chart, ram As String, ram1 As String, num As Long
num = InputBox("Please Enter the Sheet Number", "Sheet Number")
'To execute code in particular sheet number
ram = Worksheets(num).Range("AY4").End(xlDown).Address(False, False)
ram1 = Worksheets(num).Range("AZ4").End(xlDown).Address(False, False)
Set Newchart = Charts.Add
With Newchart
.ChartType = xlXYScatterLinesNoMarkers
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = "=""Values"""
.SeriesCollection(1).XValues = Worksheets(num).Range("AY4", ram)
.SeriesCollection(1).Values = Worksheets(num).Range("AZ4", ram1)
End With
Application.DisplayAlerts = False
Sheets("Ravi").Delete
'*sheet named ravi is deleted along with code*
Application.DisplayAlerts = True
Newchart.Name = "Ravi"
'How to get another code in this Ravi Chart sheet module?
Sheets("Ravi").Activate
End Sub
下面是Chartsheet代码,即使在删除和替换之后也会出现在图表工作表模块中。
Sub Chart_mouseup(ByVal Button As Long, ByVal Shift As Long, _ByVal x As Long, ByVal y As Long)
Dim ElementID As Long, Arg1 As Long, Arg2 As Long
Dim myX As Variant, myY As Double
With ActiveChart
' Pass x & y, return ElementID and Args
.GetChartElement x, y, ElementID, Arg1, Arg2
' Did we click over a point or data label?
If ElementID = xlSeries Or ElementID = xlDataLabel Then
If Arg2 > 0 Then
' Extract x value from array of x values
myX = WorksheetFunction.Index _
(.SeriesCollection(Arg1).XValues, Arg2)
' Extract y value from array of y values
myY = WorksheetFunction.Index _
(.SeriesCollection(Arg1).Values, Arg2)
' Display message box with point information
MsgBox "Series " & Arg1 & vbCrLf _
& """" & .SeriesCollection(Arg1).Name & """" & vbCrLf _
& "Point " & Arg2 & vbCrLf _
& "X = " & myX & vbCrLf _
& "Y = " & myY
End If
End If
End With
End Sub
答案 0 :(得分:0)
您需要在图表的代码模块之外创建一个单独的类模块来处理任何图表中的事件,然后使用其他代码将此类链接到您需要捕获其事件的图表。
基本上,您添加了一个类模块,并将其命名为C_ChartEvents
。包括您放置在图表代码模块中的事件代码,并在声明部分(正好在Option Explicit
下面)插入
Public With Events Cht As Chart
然后修改现有代码以使用Cht_而不是Chart_作为每个事件过程名称的前缀,例如,
Sub Cht_MouseUp(ByVal Blah As Blah...)
在创建新图表的代码模块的顶部,插入:
Dim clsChartEvents As New C_ChartEvents
创建图表后(例如,在使用NewChart
/ End With
块之后)插入:
Set clsChartEvents.Cht = NewChart
现在,NewChart将使用C_ChartEvents
中的程序回复事件。
我编写了一个教程Chart Events in Microsoft Excel,其中包含更多详细信息。