下面的代码将允许您从工作表中检索所有唯一的站名称并将它们放入Stations()
字符串数组中。
Dim TopRowOfData As Integer
Dim StationNameColumn As Integer
Dim Stations() As String
Sub GetUniqueChartNames()
Dim rngTmp As Range
Dim outRange As Range
'Select the first data cell of the Station name column.
Cells(TopRowOfData, StationNameColumn).Select
'Select the rest of the data in the column.
Range(Selection, Selection.End(xlDown)).Select
'Assign this data to a range variable.
Set rngTmp = Selection
'Find a row that occurs below the area of the range data. This will be used
'to paste the filtered values into temporarily.
outRow = rngTmp.Row + rngTmp.Rows.Count + 10 '10 is arbitrary, could be any number.
Set outRange = Cells(outRow, 1)
'Filter the data values by unique values and paste the results into the outRange area.
rngTmp.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=outRange, Unique:=True
'Get the output results of the filter operation and store them in a range object.
'outRow contains the heading of the filtered column. outRow + 1 is where the data starts.
Cells(outRow + 1, 1).Select
Range(Selection, Selection.End(xlDown)).Select
Dim rngFinal As Range
Set rngFinal = Selection
'Add the output results into the Stations array.
ReDim Stations(rngFinal.Rows.Count - 1)
Dim i As Integer
For i = 0 To rngFinal.Rows.Count - 1
Stations(i) = Cells(rngFinal.Row + i, rngFinal.Column).Value
Next
'Delete the temporary range.
rngFinal.Clear
End Sub
TopRowOfData
变量就是这样,一个整数告诉你的代码最上面一行是数据开始的地方 。StationNameColumn
是包含站名的列的编号(A=1、B=2 等)
获得站名数组后,您可以逐步通过站名列并检索与数组中每个项目关联的所有数据值。然后根据该数据创建单独的图表。
或者,您可以逐一检查站名列中的值,只检索与当前站名关联的第一行和最后一行的地址,然后根据该数据创建图表。下面的代码将执行此操作,假设您的数据按站点名称排序,以便所有相同的站点名称组合在一起。
Sub FindRowsAssociatedWithStationName()
Dim i As Integer
Dim j As Integer
Dim rng As Range
'Temp variables to store the first and last row numbers.
Dim first As Integer
Dim last As Integer
'Loop through all of the station names.
For i = 0 To UBound(Stations)
'Select the first data cell of the station names column.
Cells(TopRowOfData, StationNameColumn).Select
'Select the rest of the data in the column.
Range(Selection, Selection.End(xlDown)).Select
'Assign this data to a range variable.
Set rng = Selection
'Initialize both of the row number variables to 0.
first = 0
last = 0
'Loop through all the data rows.
For j = 0 To rng.Rows.Count - 1
If Cells(rng.Row + j, StationNameColumn).Value = Stations(i) Then
'Set the first variable.
If first = 0 Then
first = rng.Row + j
End If
'Set the last variable.
last = rng.Row + j
End If
Next
'Call a method to create the actual charts, passing in the first and last row associated with the current Station name.
Call CreateChart(first, last)
Next
End Sub
然后,您创建实际图表的代码可以使用第一个和最后一个(行)的值来检索这些行的适当数据。