簡體   English   中英

VBA Excel 宏錯誤,預期:列表分隔符或)

[英]VBA Excel Macro Error , Expected: list separator or )

我是 Excel VBA 的新用戶,最近我在嘗試運行宏時遇到此錯誤。 我的宏所做的是通過讀取單元格行數據並自己創建一個圖表用於導出等。

下面是我的宏代碼

Sub CombinationChart()

    Dim lastrow As String
    Dim boundaryRow As String
    
    ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
    lastrow = mySheet.Range("A" & Rows.Count).End(xlUp).Row
    boundaryRow = lastrow - 20
    ActiveChart.SetSourceData Source:=Range("mySheet!$A$" & boundaryRow ":$B$" & lastrow)  'make sure the range is correct here
    ActiveChart.FullSeriesCollection(1).ChartType = xlLine 'select which column should be the Line or the Column
    ActiveChart.FullSeriesCollection(1).AxisGroup = 1
End Sub

錯誤部分在這里

ActiveChart.SetSourceData Source:=Range("mySheet!$A$" & boundaryRow ":$B$" & lastrow)  'make sure the range is correct here

我的最后一行變量是包含 excel 表中的數據的最后一行,而 boundaryRow 是一個變量,它獲取最后一行值並將其減去 20,即最后一行 - 20,但我只是找不到一種方法來放入我的將兩個變量放入我的 ActiveChart.Range。

您錯過了問題行中的連接運算符( & )。

以下是它的外觀:

ActiveChart.SetSourceData Source:=Range("mySheet!$A$" & boundaryRow & ":$B$" & lastrow)  

boundaryRow":$B$"之間缺少&

以下是如何使用Range object 變量執行您想要的操作。 我在這里假設 - 因為您使用它來計算lastRow - 您已將mySheet定義為Worksheet object(可能是全局的)。

Sub CombinationChart()

    Dim lastrow As Long
    Dim boundaryRow As Long
    Dim chartData as Range
     
    ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
    lastrow = mySheet.Range("A" & Rows.Count).End(xlUp).Row 'mySheet is defined elsewhere
    boundaryRow = lastrow - 20
    Set chartData = mySheet.Cells(boundaryRow,1).Resize(21,2) ' 21 rows x 2 columns

    ActiveChart.SetSourceData Source:=chartData  'make sure the range is correct here
    ActiveChart.FullSeriesCollection(1).ChartType = xlLine 'select which column should be the Line or the Column
    ActiveChart.FullSeriesCollection(1).AxisGroup = 1
End Sub

您也可以“即時”執行此操作,將我分配給chartData的表達式替換為SetSourceData Source參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM