|
Alejandro67 Пользователь Сообщений: 19 |
#1 16.10.2014 01:08:09 Уважаемые, подскажите как изменить код, что бы диаграммы строились в определенном месте видимой области листа. или же в определенном месте. Код такой:
Соответственно все диаграммы строятся на одном и том же месте, друг за другом.
которое не работает
Увы, и этот метод снова не работает. |
|||||
|
Андрей VG Пользователь Сообщений: 11878 Excel 2016, 365 |
#2 16.10.2014 07:02:37 Доброе время суток
на следующий код
Успехов. |
||||
|
Alejandro67 Пользователь Сообщений: 19 |
#3 16.10.2014 09:49:54 Спасибо, Работает, только надо потом вернуть выделение
данный код соответственно будет размещать график по координатам листа. Если надо разместить график по координатам относительно видимой части листа то нужен такой код:
|
||||||
|
Максим Зеленский Пользователь Сообщений: 4646 Microsoft MVP |
#4 16.10.2014 13:07:33
любопытный эффект. Не думал, что Increment именно так работает — отсылок на видимый диапазон в справке нет F1 творит чудеса |
||
|
apelmon Пользователь Сообщений: 1 |
Здравствуйте. Помогите пожалуйста. Не могу запустить записаный макрос. Ошибку в коде выдает на строке ActiveSheet.Shapes.AddChart.Select. |
|
Dima S Пользователь Сообщений: 2063 |
#6 19.03.2017 14:18:55
потому что это не так)
у меня запускается) вашего не вижу. |
||||
Since you want the chart to be on a new sheet,
you have to change the macro’s «Sheet1» to new worksheet’s name,
The following macro should work for you, I have named the new worksheet as newWs
And fyi, your macro’s error message I believe is due to trying to creating 2 pivot table of the same name on «Sheet1» is not allowed.
He also like to know what to create pivotTable base on Selected Area, so I have done modification to the code.
Edited: I Assume you select 2 columns each time
Sub chart1()
'
' chart1 Macro
'
'
Dim selectedSheetName As String
Dim newWs As Worksheet
Dim rangeName As String
Dim header1 As String
Dim header2 As String
header1 = ActiveSheet.Cells(1, Selection.Column).Value
header2 = ActiveSheet.Cells(1, Selection.Column + 1).Value
selectedSheetName = ActiveSheet.Name
rangeName = Selection.Address
Set newWs = Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
selectedSheetName & "!" & rangeName, Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:=newWs.Name & "!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion12
newWs.Activate
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header1)
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header2)
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields(header2), "Count of answer1", xlCount
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header2)
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields(header2).Orientation = _
xlHidden
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header2)
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range(newWs.Name & "!$A$3:$D$6")
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range(newWs.Name & "!$A$3:$D$6")
ActiveChart.ChartType = xlColumnClustered
End Sub
-
04-02-2015, 09:17 AM
#1

Registered User

Error 1004: ActiveSheet.Shapes.AddChart.Select
Hey there,
i’m having a problem which drives me nuts. I have the following code:
it worked fine, but all of the sudden, it stopped with the runtime error 1004 at the line «ActiveSheet.Shapes.AddChart.Select»
so, whatever i try, i am not able to produce a chart anymore.
anyone has any suggestions? i’ve look through a lot of other threads, but nothing worked for me…thanks a lot
EDIT: Strange thing i just noticed: when i add a chart manually, and then run the script again, it works all fine…
Last edited by andynewtovba; 04-02-2015 at 09:22 AM.
-
04-02-2015, 10:59 AM
#2
Re: Error 1004: ActiveSheet.Shapes.AddChart.Select
You should probably post all the code, not just where the problem starts.
Last edited by skywriter; 04-02-2015 at 11:06 AM.
As a reminder, once your original request has been fulfilled please mark this thread as SOLVED by going to the «Thread Tools» drop down list above your first post and choosing solved.
If you are happy with my help, then please consider clicking the add reputation button in the lower left hand corner of this post.

-
04-02-2015, 11:38 AM
#3

Registered User

Re: Error 1004: ActiveSheet.Shapes.AddChart.Select
sure, here you go 😛
and thanks for the reply
-
04-02-2015, 12:08 PM
#4
Re: Error 1004: ActiveSheet.Shapes.AddChart.Select
Well I can’t figure it out, but I did find a lot of other threads and hits on Google when I typed «activesheet.shapes.addchart.select error 1004»
Other Excel Forum Thread
I’m not much of a chart expert, but it seems like this problem has been noticed by quite a few people, hopefully you will find an answer.
Good Luck!!!

Private Sub Command1_Click()
Dim objExcel As Object
Set objExcel = CreateObject(«Excel.Application»)
With objExcel
.Workbooks.Add
.Worksheets(1).Activate
For i = 1 To 30
.Worksheets(1).Cells(i, 1) = i
.Worksheets(1).Cells(i, 2) = Rnd(i) * 10
Next
.Charts.Add
.Visible = True
With .ActiveChart
.ChartType = xlLine
.SetSourceData Source:=Sheets(«Лист1»).Range(«B1:B30»), PlotBy:=xlColumns
.Location Where:=xlLocationAsNewSheet
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = «время»
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = «данные1»
.HasTitle = True
.HasAxis(xlCategory, xlPrimary) = True
.HasAxis(xlValue, xlPrimary) = True
.Axes(xlCategory, xlPrimary).CategoryType = xlAutomatic
‘.HasMajorGridlines = True
‘.HasMinorGridlines = False
With .Axes(xlValue)
.HasMajorGridlines = True
.HasMinorGridlines = False
End With
.HasDataTable = False
.PlotArea.Select
End With
With .Selection.Border
.ColorIndex = 16
.Weight = xlThin
.LineStyle = xlContinuous
End With
With .Selection.Interior
.ColorIndex = 2
.PatternColorIndex = 1
.Pattern = xlSolid
End With
.ActiveChart.SeriesCollection(1).Select
With .Selection.Border
.ColorIndex = 41
.LineStyle = xlContinuous
End With
With .Selection
.MarkerBackgroundColorIndex = xlAutomatic
.MarkerForegroundColorIndex = xlAutomatic
.MarkerStyle = xlNone
.Smooth = False
.MarkerSize = 7
.Shadow = False
End With
.ActiveChart.SeriesCollection(1).Select
With .Selection.Border
.ColorIndex = 57
.LineStyle = xlContinuous
End With
With .Selection
.MarkerBackgroundColorIndex = xlNone
.MarkerForegroundColorIndex = xlNone
.MarkerStyle = xlNone
.Smooth = False
.MarkerSize = 3
.Shadow = False
End With
.ActiveChart.Axes(xlValue).MajorGridlines.Select
With .Selection.Border
.ColorIndex = 57
.Weight = xlHairline
.LineStyle = xlDot
End With
With .Selection.Border
.ColorIndex = 57
.Weight = xlHairline
.LineStyle = xlDot
End With
.ActiveChart.Axes(xlCategory).Select
With .Selection.TickLabels
.Alignment = xlCenter
.Offset = 100
.ReadingOrder = xlContext
.Orientation = xlUpward
End With
With .ActiveChart.Axes(xlCategory)
.CrossesAt = 1
.TickLabelSpacing = 1
.TickMarkSpacing = 1
.AxisBetweenCategories = True
.ReversePlotOrder = False
End With
.ActiveChart.Location Where:=xlLocationAsNewSheet, Name:=»График_1″
.Sheets(«График_1»).Select
.ActiveWindow.Zoom = 80
End With
Set objExcel = Nothing
End Sub
При создании новой диаграммы на ней появляется тьма рядов.
Причем, что интересно, такое получается не всегда, иногда она создается пустой и новые ряды вставляются строго так, как указано в коде.
Вроде бы это связано с какими-то умолчаниями в Excele, который таким образом «помогает» юзеру.
Как с этим бороться, чтобы создавались строго пустые диаграммы?
Прилагаю код:
| Visual Basic | ||
|
Добавлено через 4 минуты
Здесь SWRow это строка на странице SW, откуда берутся данные для графика.
На следующей строке 1+SWRow расположена копия строки SWRow. Это нужно для того, чтобы при изменении строки SWRow можно было отслеживать изменения.
В коде создаются две серии, вторая с именем Copy.
Так вот, иногда появляется тьма серий с активной страницы, которых никто не «заказывал».
Как с этим бороться?
Слышал, что для этого надо активировать пустую страницу, или что-то вроде этого, а потом возвращаться на ту, на которой строится график.
Неужели нет путного способа?
Добавлено через 41 минуту
Оказывается, прямо здесь предлагалось решение — при создании диаграммы полностью удалять все серии на ней.
Работа с диаграммами: при создании графика непроизвольно появляются ряды данных
Вопрос, вот такой код пойдёт:
| Visual Basic | ||
|
Добавлено через 11 минут
=============
Работает!
Единственно, надо переменную MySeries как-то описать.
Поскольку с типами в диаграммах страшные заморочки, я объявил его как Object, пошло …
Добавлено через 1 час 43 минуты
Хотя без проколов не обошлось, надо сказать.
Активированное состояние может запросто слететь само собой, так что ActiveChart.SeriesCollection станет Nothing.
При этом ошибки не будет, но работа процедуры на этом закончится, т.е. все последующие действия не будут выполнены.
On Error Resume Next не поможет, потому что обращение к Nothing как к коллекции ошибкой не является.
Поэтому перед прогоном цикла For Each надо активировать Диаграмму
| Visual Basic | ||
|
А вот если Диаграмма активна, но коллекция пуста, тогда On Error работает.
В итоге надо вот так:
| Visual Basic | ||
|
0
RoryA
MrExcel MVP, Moderator
-
#2
You appear to be setting the title for the primary value axis twice — are you sure the first one shouldn’t be the category axis?
-
#3
I recorded some of that code, but my understanding is that «category axis» is set on the previous line:
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
…and that the «primary» in the line in question above refers to the fact that it’s the primary axis for the category (or x) axis. This is why primary appears again further down. That’s the primary axis for the value (or y) axis.
Could be wrong, though. Any suggestions for other things to try?
RoryA
MrExcel MVP, Moderator
-
#4
I think you missed my point:
Rich (BB code):
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "Productivity"
ActiveChart.ChartArea.Select
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleRotated)
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "Employee"
shouldn’t the first of those be:
Rich (BB code):
ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Text
-
#5
Indeed I did miss your point. Thanks for clarifying. That did the trick!
My only confusion is this: why was the VBA recorder wrong? That particular line was recorded as you see above for the category axis. Strange. At any rate, appreciate the help.
Andrew
RoryA
MrExcel MVP, Moderator
-
#6
With Excel 2007 you are lucky if you get any code at all using the macro recorder when working with charts. It’s fundamentally broken.
-
#7
I have the same problem but the solution posted here doesn’t work.
I’m an absolute noob with excel, my aim is to simply automate the labourious task of creating a chart. I have macrod the S**T out of this worksheet but can’t find the solution.
this is the table im trying to make a histogram from:
| -0.03 | 4 |
| -0.027 | 3 |
| -0.024 | 5 |
| -0.021 | 5 |
| -0.018 | 20 |
| -0.015 | 23 |
| -0.012 | 45 |
| -0.009 | 100 |
| -0.006 | 201 |
| -0.003 | 330 |
| 0 | 607 |
| 0.003 | 521 |
| 0.006 | 341 |
| 0.009 | 207 |
| 0.012 | 95 |
| 0.015 | 45 |
| 0.018 | 28 |
| 0.021 | 17 |
| 0.024 | 4 |
| 0.027 | 3 |
| 0.03 | 3 |
| More | 4 |
<tbody>
</tbody>
Code:
Sub Chart()
'
' Chart Macro
'
'
Range("K12:L33").Select
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range( _
"'FX Returns distribution'!$K$12:$L$33")
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
ActiveChart.Axes(xlCategory).HasTitle = True
ActiveChart.Axes(xlCategory).AxisTitle.Select
ActiveChart.Axes(xlCategory).AxisTitle.Select
ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Return Ranges"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Return Ranges"
With Selection.Format.TextFrame2.TextRange.Characters(1, 13).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
With Selection.Format.TextFrame2.TextRange.Characters(1, 13).Font
.BaselineOffset = 0
.Bold = msoFalse
.NameComplexScript = "+mn-cs"
.NameFarEast = "+mn-ea"
.Fill.Visible = msoTrue
.Fill.ForeColor.RGB = RGB(89, 89, 89)
.Fill.Transparency = 0
.Fill.Solid
.Size = 10
.Italic = msoFalse
.Kerning = 12
.Name = "+mn-lt"
.UnderlineStyle = msoNoUnderline
.Strike = msoNoStrike
End With
ActiveChart.Axes(xlCategory).HasTitle = True
ActiveChart.Axes(xlCategory).AxisTitle.Select
ActiveChart.Axes(xlCategory).AxisTitle.Select
ActiveChart.Axes(xlValue).AxisTitle.Select
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "Frequency"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Frequency"
With Selection.Format.TextFrame2.TextRange.Characters(1, 9).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
With Selection.Format.TextFrame2.TextRange.Characters(1, 9).Font
.BaselineOffset = 0
.Bold = msoFalse
.NameComplexScript = "+mn-cs"
.NameFarEast = "+mn-ea"
.Fill.Visible = msoTrue
.Fill.ForeColor.RGB = RGB(89, 89, 89)
.Fill.Transparency = 0
.Fill.Solid
.Size = 10
.Italic = msoFalse
.Kerning = 12
.Name = "+mn-lt"
.UnderlineStyle = msoNoUnderline
.Strike = msoNoStrike
End With
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Open to Open Returns"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Open to Open Returns"
With Selection.Format.TextFrame2.TextRange.Characters(1, 20).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
With Selection.Format.TextFrame2.TextRange.Characters(1, 20).Font
.BaselineOffset = 0
.Bold = msoFalse
.NameComplexScript = "+mn-cs"
.NameFarEast = "+mn-ea"
.Fill.Visible = msoTrue
.Fill.ForeColor.RGB = RGB(89, 89, 89)
.Fill.Transparency = 0
.Fill.Solid
.Size = 14
.Italic = msoFalse
.Kerning = 12
.Name = "+mn-lt"
.UnderlineStyle = msoNoUnderline
.Spacing = 0
.Strike = msoNoStrike
End With
ActiveChart.ChartArea.Select
With Selection.Format.TextFrame2.TextRange.Font.Line
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorAccent1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
End With
ActiveSheet.Shapes("Chart 9").IncrementLeft 298.1250393701
ActiveSheet.Shapes("Chart 9").ScaleHeight 1.9908850977, msoFalse, _
msoScaleFromBottomRight
ActiveSheet.Shapes("Chart 9").ScaleHeight 0.728144782, msoFalse, _
msoScaleFromTopLeft
ActiveSheet.Shapes("Chart 9").IncrementLeft -35.6249606299
ActiveSheet.Shapes("Chart 9").IncrementTop 1.8750393701
ActiveSheet.Shapes("Chart 9").ScaleWidth 1.4062495626, msoFalse, _
msoScaleFromTopLeft
End Sub
Maybe you
-
#8
@Rizzen
When I step through the code by placing the cursor within the sub and continually hitting F8, I see that the value axis title doesn’t actually get added to the chart when this line is executed…
Code:
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
Therefore, since the value axis title doesn’t exist, I get an error once this line is executed…
Code:
ActiveChart.Axes(xlValue).AxisTitle.Select
So it’s likely the same thing is happening with you. Try something like this…
Code:
Sub CreateChart()
Dim oSeries As Series
Dim rSourceData As Range
Set rSourceData = Worksheets("FX Returns distribution").Range("$K$12:$L$33")
With ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Chart
Do While .SeriesCollection.Count > 0
.SeriesCollection(1).Delete
Loop
.SetSourceData Source:=rSourceData
.SetElement msoElementChartTitleAboveChart
.SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
.SetElement msoElementPrimaryValueAxisTitleBelowAxis
.ChartTitle.Text = "Open to Open Returns"
.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Return Ranges"
.Axes(xlValue, xlPrimary).AxisTitle.Text = "Frequency"
With .ChartArea.Format.TextFrame2.TextRange.Font.Line
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorAccent1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
End With
End With
End Sub
Hope this helps!
-
#9
I have another question: this spread sheet has multiple histograms so I thought it would be enough to declare a new series and range. I’d also like to move the charts away from each other to T12 and T37 respectively. I played around with all the numbers and even declared a new chart variable but for some reason chart two won’t add a title (runtime error).
Code:
Sub CreateChart()
Dim oSeries As Series
Dim rSourceData As Range
Set rSourceData = Worksheets("FX Returns distribution").Range("$K$12:$L$33")
With ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Chart
Do While .SeriesCollection.Count > 0
.SeriesCollection(1).Delete
Loop
.SetSourceData Source:=rSourceData
.SetElement msoElementChartTitleAboveChart
.SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
.SetElement msoElementPrimaryValueAxisTitleBelowAxis
.ChartTitle.Text = "Open to Open Returns"
.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Return Ranges"
.Axes(xlValue, xlPrimary).AxisTitle.Text = "Frequency"
End With
Dim pSeries As Series
Dim tSourceData As Range
Dim vChart As Chart
Set tSourceData = Worksheets("FX Returns distribution").Range("$K$37:$L$57")
With ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Chart
Do While .SeriesCollection.Count > 1
.SeriesCollection(1).Delete
Loop
.SetSourceData Source:=tSourceData
.SetElement mspElementChartTitleAboveChart
.SetElement mspElementPrimaryCategoryAxisTitleBelowAxis
.SetElement mspElementPrimaryValueAxisTitleBelowAxis
.ChartTitle.Text = "High to Low Returns"
.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Return Ranges"
.Axes(xlValue, xlPrimary).AxisTitle.Text = "Frequency"
End With
End Sub
-
#10
For the second chart, it should be…
Code:
.SetElement msoElementChartTitleAboveChart
.SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
.SetElement msoElementPrimaryValueAxisTitleBelowAxis