MS VBA,按用户更改图表的数据范围

时间:2016-07-07 19:19:13

标签: excel vba excel-vba graph range

有两个ListBox,一个包含所有Automotive Parts的名称,另一个是用户选择的部分。

The List Boxes

每个零件都有零件的名称,生产日期和生产线的生产能力。目标是,一旦用户选择他/她想要看哪些部分如何影响线的容量,当他/她按下“让我成为图表”按钮时,会出现一个条形图,其中他/她选择的部分。

我为所选的每个名称使用了两个For循环和一个If then语句,并且对于所有部分名称所在范围内的每个单元格,它将查找该名称,一旦找到,它将创建一个包含的范围该部分的名称,生产日期和容量。最后,它会使用 Union 命令将该范围添加到图表的范围。

但是,当代码运行时,只有当前容量和最后部件名称出现在图表上(两个条形图)。

关于我做错了什么想法?

Dim actualrange As Range
Dim totalrange As Range
Dim c As Range
Dim workingrange As Range
Dim findingnameo As Long
Set totalrange = Range("M1:DA1")
Dim p As Long
Dim tryingrange As Range
For p = 0 To SelectedListBox.ListCount - 1
  For Each c In totalrange.Cells
        If c.Text = SelectedListBox.List(p) Then

         findingnameo = Sheets("The Master").Range("M1:DA1").Find(c.Value, searchdirection:=xlNext, SearchOrder:=xlByColumns).Column

         Dim thename As Range
         Dim thedate As Range
         Dim thecap As Range

         Set thename = Cells(1, findingnameo)
         Set thedate = Cells(2, findingnameo)
         Set thecap = Cells(3, findingnameo)

          Set workingrange = Union(thename, thedate, thecap)

           Dim currentcap As Range

          Set currentcap = Range("M1:M3")

         Set actualrange = Union(currentcap, workingrange)

End If


Next c


Next p

谢谢!

1 个答案:

答案 0 :(得分:0)

认为它比实际上更复杂......

Dim currentcap As Range

          Set currentcap = Range("M1:M3")
            Set actualrange = currentcap

For p = 0 To SelectedListBox.ListCount - 1
  For Each c In totalrange.Cells
        If c.Text = SelectedListBox.List(p) Then

         findingnameo = Sheets("The Master").Range("M1:DA1").Find(c.Value, searchdirection:=xlNext, SearchOrder:=xlByColumns, LookAt:=xlWhole).Column

         Dim thename As Range
         Dim thedate As Range
         Dim thecap As Range

         Set thename = Cells(1, findingnameo)
         Set thedate = Cells(2, findingnameo)
         Set thecap = Cells(3, findingnameo)

          Set workingrange = Union(thename, thedate, thecap)



         Set actualrange = Union(actualrange, workingrange)

End If


Next c


Next p

我只需要做到

set actualrange= Union(actualrange,workingrange)

而不是

set actualrange = Union(currentcap, workingrange)

你从错误中学到了什么?

虽然请分享任何提示或技巧,但我想学习!