使用 Range.Address 时 VBA 中图表集源数据的运行时错误

Runtime Error for Chart Set Source Data in VBA while using Range.Address

我正在尝试将数据源从一个 sheet 放到另一个 sheet 的图表中。我能够实现数据收集,但最后,当我们设置源数据时,它抛出 运行 时间错误 1004 - 对象'_Global' 的方法 'Range' 失败。

以下是我使用的代码

Sub UBCharts()

Set Wb = ThisWorkbook
Set WsCharts = Wb.Sheets("Trend Charts")
Set UBMainChart = WsCharts.ChartObjects("UBMainChart")
Set UBMonthlyYTDSht = Wb.Worksheets("UM - Monthly & YTD Trend")
YearValue = WsCharts.Range("A1").Value
'LookupDate = CDate("" & "01/01/" & YearValue & "")

Xrows = UBMonthlyYTDSht.Range("A" & Rows.Count).End(xlUp).Row
MatchStartRow = Application.WorksheetFunction.Match(CLng(CDate(DateSerial(YearValue, 1, 1))), UBMonthlyYTDSht.Columns("A:A"), 0)
MatchEndRow = Application.WorksheetFunction.Match(CLng(CDate(DateSerial(YearValue, Month(CLng((DateAdd("m", -1, Date)))), 1))), UBMonthlyYTDSht.Columns("A:A"), 0)
UBMainChart.Activate

'ActiveChart.SetSourceData Source:=Range("'UM - Monthly & YTD Trend'!$A:$L,'UM - Monthly & YTD Trend'!$A:$L")
UBMainChart.Chart.ChartArea.ClearContents
On Error Resume Next
UBMonthlyYTDSht.Activate
Set ChartRange = UBMonthlyYTDSht.Range(Cells(MatchStartRow, 1), Cells(MatchEndRow, Lcols))
Set ChartRngTitles = UBMonthlyYTDSht.Range(Cells(1, 1), Cells(1, Lcols))
On Error GoTo 0

UBMainChart.Activate
RngStr = """'" & UBMonthlyYTDSht.Name & "'!" & ChartRngTitles.Address & "," & "'" & UBMonthlyYTDSht.Name & "'!" & ChartRange.Address & """"
ActiveChart.SetSourceData Source:=Range(RngStr), PlotBy:=xlColumns 'I'm getting error here
'"'UM - Monthly & YTD Trend'!$A:$L,'UM - Monthly & YTD Trend'!$A:$L"

End Sub

感谢您的帮助!

在这里使用 Union 可能更容易:

UBMainChart.SetSourceData Source:=Union(ChartRangeTitles, ChartRange), PlotBy:=xlColumns