代码之家  ›  专栏  ›  技术社区  ›  Chris

VBA运行时1004错误

  •  1
  • Chris  · 技术社区  · 10 年前

    我在VBA上遇到了运行时1004错误。我知道问题是什么,但我就是找不到解决办法。

    我正在使用Microsoft Excel 2013

    样本数据如下:

    1   01/19/2015  40  0.250006538
                    52  0.052997791
                    58  0.010990106
    2   01/20/2015  40  0.250001126
                    52  0.052997369
                    58  0.010990412
    3   01/21/2015  40  0.250005088
                    52  0.052996605
                    58  0.010990819
    

    我想做的是提取某个数字旁边的数据值(例如,对于40,它将是0.250006538、0.250001126、0.250005088等),并将它们绘制在图表上。

    到目前为止,我所做的是将这些范围结合在一起:

    'checks for number 40
    For each c In rng1.Cells
            Set cellRange = Range("D" & c.Row)
            Set cCell1 = Union(cCell1, cellRange)
    Next
    

    我也尝试过这种方法:

     'checks for number 40
     For each c In rng1.Cells
        If Not s = vbNullString Then
               s = s & "," & Range("D" & c.Row).address
        Else
               s = Range("D" & c.Row).address
        End If
     Next
    

    我将得到的最终结果是cCell1变量或带有地址列表的s变量。

     $D$2,$D$5,$D$8,$D$11,$D$14,$D$17,$D$20,$D$23,$D$26,$D$29,$D$32,$D$35,$D$38,$D$41,$D$44,$D$47,$D$50,$D$53,$D$56,$D$59,$D$62,$D$65,$D$68,$D$71,$D$74,$D$77,$D$80,$D$83,$D$86,$D$89,$D$92,$D$95,$D$98,$D$101,$D$104,$D$107,$D$110,$D$113,$D$116,$D$119,$D$122,$D$125,$D$128,$D$131,$D$134,$D$137,$D$140,$D$143,$D$146,$D$149,$D$152,$D$155,$D$158,$D$161,$D$164,$D$167,$D$170,$D$173,$D$176,$D$179,$D$182,$D$185,$D$188,$D$191,$D$194,$D$197,$D$200,$D$203,$D$206,$D$209,$D$212,$D$215,$D$218,$D$221,$D$224,$D$227,$D$230,$D$233,$D$236,$D$239,$D$242
    

    问题是当我试图用

     ActiveChart.SeriesCollection(1).Values = Range(cCell1.address)
    

     ActiveChart.SeriesCollection(1).Values = Range(s)
    

    它停止并给我一个运行时错误“1004”。

    我假设发生这种情况是因为变量中的地址太长,无法用Range函数处理……我正在处理的数据表有数百到数千个数据,必须根据点数绘制图表。

    对此有什么变通办法吗?非常感谢!

    1 回复  |  直到 10 年前
        1
  •  0
  •   Tim Williams    10 年前

    这对我有用。。。

    Sub Tester()
    
        Dim c As Range, cTot As Range, s As Series
    
        'collect all values for "40"
        For Each c In Range("D1:D27").Cells
            If c.Offset(0, -1) = 40 Then
                If cTot Is Nothing Then
                    Set cTot = c
                Else
                    Set cTot = Application.Union(cTot, c)
                End If
            End If
        Next c
    
        'create new series
        Set s = ActiveSheet.ChartObjects(1).Chart.SeriesCollection.NewSeries()
    
        s.Values = cTot  'set values
    
    End Sub