如何在非连续列中选择一个单元格范围,直到最后一个空行?

时间:2019-06-28 10:48:38

标签: excel vba

我正在使用宏从数据库中创建图表,并且需要在最后一个非空行的3个非连续列(A,D和K)中选择数据。

Private Sub TRAFFIC_BT_Click()
'
' web_traffic Macro
' Create a chart to show the evolution of web_traffic stats
'

'
    Dim szTodayDate As String
    Dim LastRow As Long
    Dim WS As Worksheet


    Set WS = Sheets("DB")

    LastRow = WS.Range("A" & Rows.Count).End(xlUp).Row 'Finds the last row with text


    szTodayDate = Format(Date, "mmm-dd-yyyy")
    Application.ScreenUpdating = False
    ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
    ActiveChart.ChartTitle.Text = "Web Traffic Report " + szTodayDate
    ActiveChart.SetSourceData Source:=Range("DB!A1:A72, DB!$D1:$D72, DB!$K1:$K72")
    ActiveChart.FullSeriesCollection(1).ChartType = xlColumnClustered
    ActiveChart.FullSeriesCollection(1).AxisGroup = 1
    ActiveChart.FullSeriesCollection(2).ChartType = xlLine
    ActiveChart.FullSeriesCollection(2).AxisGroup = 1
    ActiveChart.FullSeriesCollection(2).AxisGroup = 2
    ActiveChart.SetElement (msoElementLegendBottom)
    ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Web Traffic report " + szTodayDate


End Sub

使用此代码,我在图表中从A1绘制到A72,从D1绘制到D72 ...但是我想为LastRow更改“ 72”

1 个答案:

答案 0 :(得分:0)

将lastrow变量连接到该范围内,而不是使用72。

Private Sub TRAFFIC_BT_Click()
'
' web_traffic Macro
' Create a chart to show the evolution of web_traffic stats
'

'
    Dim szTodayDate As String
    Dim LastRow As Long
    Dim WS As Worksheet



    Set WS = Sheets("DB")

    LastRow = WS.Range("A" & Rows.Count).End(xlUp).Row 'Finds the last row with text


    szTodayDate = Format(Date, "mmm-dd-yyyy")
    Application.ScreenUpdating = False
    ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
    ActiveChart.ChartTitle.Text = "Web Traffic Report " + szTodayDate

    ActiveChart.SetSourceData Source:=Range("DB!A1:A" & lastrow & ", DB!$D1:$D" &  lastrow & ", DB!$K1:$K" & lastrow & ")

    ActiveChart.FullSeriesCollection(1).ChartType = xlColumnClustered
    ActiveChart.FullSeriesCollection(1).AxisGroup = 1
    ActiveChart.FullSeriesCollection(2).ChartType = xlLine
    ActiveChart.FullSeriesCollection(2).AxisGroup = 1
    ActiveChart.FullSeriesCollection(2).AxisGroup = 2
    ActiveChart.SetElement (msoElementLegendBottom)
    ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Web Traffic report " + szTodayDate


End Sub