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

时间:2017-05-12 19:08:37

标签: excel vba excel-vba

我正在编写一些旨在与Excel 2007及更新版本兼容的VBA代码。从Excel 2013开始,我们引入了Chart Series Filtering选项和相关的Chart.FullSeriesCollection对象,我在我的代码中包含If语句来选择此对象或较旧的.SeriesCollection取决于在Excel版本上。

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

如何让旧的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]

2 个答案:

答案 0 :(得分:3)

您可以使用compiler constants,例如

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

答案 1 :(得分:0)

您应该能够通过将图表转换为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