Excel VBA 通过存储在变量中的名称访问 FullSeriesCollection 时出现运行时错误 13

Excel VBA Runtime error 13 when accessing FullSeriesCollection via a name stored in a variable

当我尝试使用 FullSeriesCollection 方法获取或设置图表的各种属性时,我 运行 遇到了一个奇怪的小问题。我可以通过索引或系列名称访问它们,但是当我尝试使用存储在变量中的名称时,我收到 运行-时间错误 13(类型不匹配)。例如:

Dim trendname As String     'I've also tried Variant, but it still gives me error 13
    trendname = "Average"   'when the name is used directly as below

Debug.Print Charts(1).FullSeriesCollection(1).Formula               'This works 
Debug.Print Charts(1).FullSeriesCollection("Average").Formula           'This works 
Debug.Print Charts(1).FullSeriesCollection.Item("Average").Formula      'This works 
Debug.Print Charts(1).FullSeriesCollection(trendname).Formula           'This gives runtime error 13
Debug.Print Charts(1).FullSeriesCollection.Item(trendname).Formula      'This gives runtime error 13
Debug.Print Charts(1).FullSeriesCollection("" & trendname).Formula      '...but this works fine!
Debug.Print Charts(1).FullSeriesCollection.Item("" & trendname).Formula 'This works too

有没有一种方法可以使它仅引用 trendname 而不需要将变量与空字符串连接起来?是否有不同的变量类型我应该声明为 trendname,而不是 Variant 或 String? 虽然连接方法确实有效,但它看起来相当愚蠢,我很好奇为什么它在仅使用变量本身不起作用时有效。

您可能已经知道,Index 参数必须是 Variant。因此,即使您将变量声明为 Variant,一旦为它分配了一个字符串,它就会被识别为一个字符串。因此,您必须使用类型转换函数 CVar...

将索引强制转换为 Variant
Debug.Print Charts(1).FullSeriesCollection(CVar(trendname)).Formula

or

Debug.Print Charts(1).FullSeriesCollection.Item(CVar(trendname)).Formula