首页 文章

Excel VBA图表

提问于
浏览
1

我在工作簿中有两张纸 . 第一张纸名称是“摘要”,另一张是“目标” . 我在摘要标签中有图表 . 我想将该图表的源数据设置为包含日期的目标选项卡 . Ex(11/01/2013 - 11/30/2013) . 每天我想更改相应日期的图表日期 . 所以我在excel vba中试过如下:

sheets("Summary ").Select
ActiveSheet.ChartObjects("Chart 3").Activate
ActiveChart.PlotArea.Select
Sheets("Target").Select
a = InputBox("enter the date - format(mm/dd/yyyy)")

Set findrow = Range("a:a").Find(what:=a, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Rows

findrownumber = findrow.Row

ActiveChart.SeriesCollection(2).Values = "='Target Chart'!R4C78:R" & findrownumber & "C78"
End sub

当我试图在公式中输入源数据值时,它显示错误 .

请帮我 .

1 回答

  • 1

    这是我尝试的代码,它的工作原理 . 我可能在创建此示例时切换了工作表的名称,但您可以在代码中更改:)

    假设“摘要”选项卡如下所示

    enter image description here

    Target Sheet中的图表目前看起来像这样 . 源数据设置为 =Summary!$A$1:$A$6

    enter image description here

    现在试试这段代码

    Option Explicit
    
    Sub Sample()
        Dim wsSum As Worksheet, wsTgt As Worksheet
        Dim objChart As ChartObject, chrt As Chart
        Dim sDate
        Dim findrow As Long
        Dim aCell As Range
    
        '~~> Accept the date
        sDate = InputBox("enter the date - format(mm/dd/yyyy)")
    
        '~~> Check if user entered something
        If sDate <> "" Then
            '~~> Set your respective worksheets
            Set wsSum = ThisWorkbook.Sheets("Summary")
            Set wsTgt = ThisWorkbook.Sheets("Target")
    
            '~~> Find the date in the cell
            With wsSum
                For Each aCell In .Columns(1).Cells
                    If Format(aCell.Value, "mm/dd/yyyy") = sDate Then
                        '~~> Get the row number
                        findrow = aCell.Row
                        Exit For
                    End If
                Next aCell
            End With
    
            '~~> Update the chart
            With wsTgt
                Set objChart = .ChartObjects("Chart 1")
                Set chrt = objChart.Chart
    
                chrt.SeriesCollection(1).Values = "='Summary'!R4C1:R" & findrow & "C1"
            End With
        End If
    End Sub
    

    运行代码时,在输入框中,将日期设置为“01/11/2013”

    enter image description here

    这是源数据设置为 =Summary!$A$4:$A$11 的输出

    enter image description here

    IMPORTANT :我不建议使用Inputbox来捕获日期 . 您可能想要使用THIS

相关问题