在Excel 2007 VBA中,无法使用Option Strict Off进行后期绑定

我在写一些VBA代码,旨在与Excel 2007和更新版本兼容。 从Excel 2013开始,图表系列过滤选项和相关的Chart.FullSeriesCollection对象被引入,我已经在我的代码中包含一个If语句来select这个对象,或者根据Excel版本select旧的.SeriesCollection

但是,由于.FullSeriesCollection ,VBA无法编译Excel 2007中的代码。 我想尝试延迟绑定,以便编译器跳过包含该未定义对象的If语句,但Excel 2007(使用VBA版本6.3)不能识别Option Strict Off行; 我只能从BaseCompareExplicitPrivateOption语句。

我怎样才能让旧的VBA编译器跳过使用.FullSeriesCollection的行? 我一直在学习VBA 3天,所以如果这是非常明显的,请原谅。

我的代码的相关部分:

 Private Sub EventChart_MouseDown(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, Arg1b As Long Dim myX As Variant, myY As Double Dim xlVrsion As Integer, verSerColl As Object xlVrsion = CInt(Left(Application.Version, 2)) 'Get Excel version and convert to an integer (2007 = 13.0; 2010 = 14.0; 2013 = 15.0; 2016 = 16.0) With ActiveChart .GetChartElement x, y, ElementID, Arg1, Arg2 If ElementID = xlSeries Then If xlVrsion >= 15 Then 'Check if Excel version is equal or newer than 2013. Set verSerColl = .FullSeriesCollection(Arg1) Else Set verSerColl = .SeriesCollection(Arg1) End If '[More irrelevant code] 

你可以使用编译器常量,比如

 #If VBA7 Then 'Check if Excel version is equal or newer than 2013. Set verSerColl = .FullSeriesCollection(Arg1) #Else Set verSerColl = .SeriesCollection(Arg1) #End If 

您应该能够通过将图表转换为Object或Variant来使用后期绑定:

 If Val(Application.Version) >= 15 Then Dim objChart ' As Variant by default Set objChart = ActiveChart Set verSerColl = objChart.FullSeriesCollection(Arg1) Else Set verSerColl = ActiveChart.SeriesCollection(Arg1) End If 

举个例子,即使你不能编译它,也可以在旧的Office版本中运行:

 Dim verSerColl If Val(Application.Version) >= 15 Then Set verSerColl = ActiveChart.FullSeriesCollection(Arg1) Else Set verSerColl = ActiveChart.SeriesCollection(Arg1) End If