处理vba数组

时间:2014-06-17 14:46:06

标签: excel-vba vba excel

这是我在这个问题上的第一个问题。我很好奇,但对VBA和编程非常环保。 我已经处理了几个星期的问题,阅读了很多帖子,但仍然感到迷茫。希望你们中的一个可以提供帮助!

这是我的代码:

Private Sub CommandButton1_Click()
Dim numbers() As Double, size As Integer, i As Integer
Dim Numchart As Chart, y_st As Variant

size = WorksheetFunction.CountA(Worksheets(6).Columns(1))

ReDim Preserve numbers(size)

For i = 2 To size
If Cells(i, 2).Value = "PROD" Then
numbers(i) = Cells(i, 8).Value
End If
Next i

y_st = convert_arr(numbers())

Set Numchart = Charts.Add
Numchart.ChartType = xlLineMarkers
Numchart.SeriesCollection.NewSeries
Numchart.SeriesCollection(1).Values = y_st

End Sub


Public Function convert_arr(pass_arr() As Double) As String
For i = 0 To UBound(pass_arr())
    Select Case i
            Case 0
                convert_arr = "{" & pass_arr(0) & ","
            Case 1 To UBound(pass_arr()) - 1
               convert_arr = convert_arr & pass_arr(i) & ","
            Case UBound(pass_arr())
                convert_arr = convert_arr & pass_arr(i) & "}"
            End Select
Next
End Function`

使用此代码,我得到一个不连续的图表,因为在“PROD”之间还有其他类别我想要过滤掉。 谢谢你提前,

1 个答案:

答案 0 :(得分:1)

我建议您使用COUNTIF限制数组大小:

'additional variables

Dim ArraySize As Long
Dim counter As Long

Size = WorksheetFunction.CountA(Worksheets(6).Columns(1))
ArraySize = WorksheetFunction.CountIf(Worksheets(6).Columns(2), "PROD") - 1
ReDim Preserve numbers(ArraySize)

For i = 2 To Size
    If Cells(i, 2).Value = "PROD" Then
        numbers(counter) = Cells(i, 8).Value
        counter = counter + 1
    End If
Next i