在VB

时间:2017-02-13 13:11:28

标签: excel vba excel-vba

我正在努力使用我的宏,我试图让图表显示有效范围。首先,我有一个重复的IF语句,它基本上决定了哪个单元格的选择取决于单元格的值(Set ab = Cells(57,19))。见下面的例子......

Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets(“Parameters”)
wb.Activate
ws.Select
Dim ab As Range
Set ab = Cells(57, 19)
Dim rng As Range

If ((ab < 2) And (ab >= 1)) Then
Range(“g77:j90”).Select
End If

If ((ab < 3) And (ab >= 2)) Then
Range(“g77:j95”).Select
End If

If ((ab < 4) And (ab >= 3)) Then
Range(“g77:j100”).Select
End If

在此之后,我希望“图表6”将此选择显示为源数据。

Dim CHARTDATA As Range

Set CHARTDATA = selection


Chart6.SetSourceData Source:=CHARTDATA, PlotBy:=xlColumns

但是,我收到错误消息“运行时错误”424“:object required”。我相信这是因为一旦图表6被改变,所选范围被取消选择?为了解决这个问题,我尝试将范围选择存储到CHARTDATA,但显然这两种方法都没有用。

如何设置通过IF语句选择的数据显示在图表6中?

欢迎任何和所有的想法,并且如果这是一个重复且非常基本的问题而道歉(我对VBA完全不熟悉)。

2 个答案:

答案 0 :(得分:0)

Option Explicit

Dim wB As Workbook
Dim wS As Worksheet
Dim aB As Double
Dim CHARTDATA As Range
Dim Ch as Chart

Set wB = ActiveWorkbook
Set wS = wB.Sheets("Parameters")

With wS
    aB = .Cells(57, 19).value

    If ((aB < 2) And (aB >= 1)) Then Set CHARTDATA = .Range("g77:j90")
    If ((aB < 3) And (aB >= 2)) Then Set CHARTDATA = .Range("g77:j95")
    If ((aB < 4) And (aB >= 3)) Then Set CHARTDATA = .Range("g77:j100")
End With 'wS

If Not CHARTDATA Is Nothing Then
    Set Ch = wS.ChartOjbects("Chart 6").Chart
    Ch.SetSourceData Source:=CHARTDATA, PlotBy:=xlColumns
Else
    MsgBox "CHARTDATA is not defined, your tests on aB are not met.", vbInformation + vbOKOnly
End If

答案 1 :(得分:0)

你可以尝试使用Select Case和#34;作弊&#34;一点点,使用WorksheetFunction.Roundup

使用Select Case可以让您以后轻松添加更多场景。

<强>代码

Option Explicit

Sub ChartRange()

Dim wB As Workbook
Dim wS As Worksheet
Dim aB As Long
Dim CHARTDATA As Range

Set wB = ActiveWorkbook
Set wS = wB.Worksheets("Parameters")

With wS
    aB = Application.WorksheetFunction.RoundDown(.Cells(57, 19).Value, 0) ' use the round down to round down to the nearest integer
    Select Case aB
        Case 1 ' (from 1 to 1.99999)
            Set CHARTDATA = .Range("G77:G90")

        Case 2 ' (from 2 to 2.99999)
            Set CHARTDATA = .Range("G77:G95")

        Case 3 ' (from 3 to 3.99999)
            Set CHARTDATA = .Range("G77:G100")

    End Select
End With

wB.Charts.Item("Chart 6").SetSourceData Source:=CHARTDATA, PlotBy:=xlColumns

End Sub