Надеюсь, это решит проблему.Я предполагаю, что rng1
выдавал ошибку, потому что он не находил Sum (FRD End Analysis) .Я не уверен, хотя, поскольку вы не говорите, какую ошибку это выдает.
Это может быть: переменная не определена (если вы используете Option Explicit
) или Переменная объекта или переменная блока не установлена , поскольку Find
Заявление не нашло ничего или ряда других вещей, о которых я не подумал.
Sub Example()
Dim wrkSht As Worksheet
Dim rFound As Range
Dim rng1 As Range
Dim cht As ChartObject
Dim DisplayRange As Range
'The code needs to know which sheet you're talking about.
'Not designating the sheet means it will look at the currently active sheet.
Set wrkSht = ThisWorkbook.Worksheets("Sheet1")
'The chart will be built to cover this range.
Set DisplayRange = wrkSht.Range("D5:H20")
'Try and find the cell and store it's reference in a range variable.
'Note that it's using wrkSht variable to identify the sheet that cells are on.
Set rFound = wrkSht.Cells.Find( _
What:="SUM(FRD End Analysis)", _
After:=wrkSht.Range("A1"), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
'If it hasn't been found then rFound will be nothing, otherwise it will not be nothing.
If Not rFound Is Nothing Then
'Here the cell 1 column to the right of rFound is considered to be cell "A1".
'So if value is found in cell B2 then .Range("A1:E2") will reference cells C2:G3 (C2 is considered to be A1)
Set rng1 = Union(wrkSht.Range("C1:G1"), rFound.Offset(, 1).Range("A1:E2"))
'Create a chart container.
Set cht = wrkSht.ChartObjects.Add _
(DisplayRange.Left, DisplayRange.Top, DisplayRange.Width, DisplayRange.Height)
'Build the chart within the chart container.
With cht
.Chart.ChartType = xlColumnClustered
'Create the series from rng1.
With .Chart.SeriesCollection.NewSeries
.Name = "First Row"
.XValues = rng1.Rows(1)
.Values = rng1.Rows(2)
End With
With .Chart.SeriesCollection.NewSeries
.Name = "Second Row"
.XValues = rng1.Rows(1)
.Values = rng1.Rows(3)
End With
End With
End If
End Sub