1

I have written the following code that is used to create a chart in an excel sheet:

Sub AddChart()

Dim sh As Worksheet
Dim chrteit As Chart

Set sh = ActiveWorkbook.Worksheets("TraceTable")
Set chrteit = sh.Shapes.AddChart.Chart

lastrows = Range("A2").End(xlDown).Row

With chrteit
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
.SeriesCollection(1).XValues = sh.Range(Cells(2, 6), Cells(lastrows, 6))
.SeriesCollection(1).Values = sh.Range(Cells(2, 7), Cells(lastrows, 7))

    Let chrteit.Parent.Name = "EIT"
    .Parent.Height = Range("N2:N14").Height
    .Parent.Width = Range("N2:T2").Width
    .Parent.top = Range("N2").top
    .Parent.Left = Range("N2").Left
    .Parent.Placement = xlFreeFloating

End With

Now after this code runs, a chart is created with the used data cells. I then have another macro run that will manipulate all the data and move it around, so I drew the charts to reference the cells easily before the data gets manipulated. Anyways, the cells are reformatted and adjust in size, so the graph stays where it is. All I want to then do is move the chart back to the left using:

Sub MoveChart()

With ActiveWorkbook.Worksheets("TraceTable")
.ChartObjects("EIT").Left = .Range("N2").Left
End With

End Sub

But I am getting an error that says "The item with the specified name wasn't found." and highlights the line:

.ChartObjects("EIT").Left = .Range("N2").Left

What is wrong with my code?! It worked once before but I'm not sure what I changed. Please help, thank you!

Community
  • 1
  • 1
art123456
  • 127
  • 2
  • 6
  • 15

1 Answers1

1

Use the ChartArea property of Chart object. See below:

Sub MoveChart()

    Dim Sh As Worksheet: Set Sh = ThisWorkbook.Sheets("TraceTable")
    Dim Shp As Chart

    With Sh
        Set Shp = .ChartObjects("EIT").Chart
        Shp.ChartArea.Left = .Range("N2").Left
    End With

End Sub

In any case, your separated macros can be summarized in one macro as follows.

Sub FullRun()

    Dim TSht As Worksheet
    Dim LCol As Long, LRow As Long
    Dim RoundOffR As Range, RoundOffC As Range
    Dim ShotR As Range, ShotC As Range
    Dim Cht As Chart
    Dim DivideR As Range, DivideC As Range

    Set TSht = ActiveWorkbook.Sheets("TraceTable")

    With TSht
        ' Get boundaries.
        LCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        ' Get top row and fill it with color.
        With .Cells(1, 1).Resize(1, LCol)
            .Interior.Color = 14136213
            .Font.Bold = True
        End With
        ' Use Union for a cleaner delete.
        ' Columns to delete are Date, Little, Deviation, F, G
        Union(.Range("D:D"), .Range("F:F"), .Range("H:H"), .Range("O:P")).Delete
        ' Initialize the range to round off.
        Set RoundOffR = .Range("E2:K" & LRow)
        RoundOffR.NumberFormat = "0"
    End With

    ' Round the values. If it's from E column, change from "0"
    ' format to "0.0000" format.
    For Each RoundOffC In RoundOffR
        RoundOffC.Value = Application.Round(RoundOffC.Value, 0)
        If RoundOffC.Column = 11 Then
            RoundOffC.NumberFormat = "0.0000"
        End If
    Next

    ' Insert new column, distribute some values
    With TSht
        With .Range("C1")
            .EntireColumn.Insert
            .Value = "Sample"
        End With
        .Range("E1").Value = "Type"
        Set ShotR = .Range("D2:D" & LRow)
    End With

    For Each ShotC In ShotR
        With ShotC
            ' Get the last two digits of D and put in E.
            .Offset(0, 1).Value = Right(.Value, 2)
            ' Get the 10th position in D, get next two characters, and put in C.
            .Offset(0, -1).Value = Right(.Value, 2)
            ' Get the last two digits in B, and replace D.
            .Value = Right(.Offset(0, -2).Value, 2)
        End With
    Next

    ' Adjust formatting and create chart.
    With TSht
        .Cells.HorizontalAlignment = xlCenter
        .Columns.AutoFit
        .Rows.AutoFit
        Set Cht = .Shapes.AddChart.Chart
    End With

    ' Manipulate chart.
    With Cht
        .Parent.Name = "EIT"
        .ChartType = xlXYScatter
        .SeriesCollection.NewSeries
        With .SeriesCollection(1)
            .XValues = TSht.Range("F2:F" & LRow)
            .Values = TSht.Range("G2:G" & LRow)
        End With
        ' User .ChartArea for size and position.
    End With

    ' "Divide" the rows.
    Set DivideR = TSht.Range("B2:B" & LRow)
    For Each DivideC In DivideR
        ' If current cell is not empty and not equal to next cell, insert a row.
        If Not IsEmpty(DivideC) And DivideC.Value <> DivideC.Offset(1, 0).Value Then
            DivideC.Offset(1, 0).EntireRow.Insert
        End If
    Next

    ' Add borders.
    TSht.Cells.SpecialCells(xlCellTypeConstants).Borders.LineStyle = xlContinuous

    ' Resize and move chart. Use .ChartArea for this.
    With Cht.ChartArea
        .Height = TSht.Range("N2:N14").Height
        .Width = TSht.Range("N2:T2").Width
        .Top = TSht.Range("N2").Top
        .Left = TSht.Range("N2").Left
    End With

End Sub

That takes care of everything from borders, column deletion, dividers, chart creation and manipulation, and so on. This is best so that your macro doesn't jump all over the place. Of course, it uses ActiveWorkbook so you can put this in another workbook and just run it while the workbook containing the TraceTable sheet is highlighted.

Hope this helps.

WGS
  • 13,969
  • 4
  • 48
  • 51
  • It gives me an error: `Subscript out of range` at the line `Set Shp = ThisWorkbook.Sheets("TraceTable")` – art123456 Jul 22 '14 at 19:42
  • That means the sheet `TraceTable` does not exist in the workbook where you placed this macro in. In any case, just use the one from your post: `ActiveWorkbook.Worksheets("TraceTable")`. – WGS Jul 22 '14 at 19:49
  • It now gives me the `The item with the specified name wasn't found.` error again at the line: `Set Shp = .ChartObjects("EIT").Chart` – art123456 Jul 22 '14 at 20:03
  • If it's not a proprietary file, can you upload the relevant file somewhere and let me have a look? – WGS Jul 22 '14 at 20:10
  • It is proprietary so I am unable to share it unfortunately. Give me a minute though and I will make an edit and enter the relevant code that I can share with you and then also a short instruction on how to setup a spreadsheet that you can use as a sample. – art123456 Jul 22 '14 at 20:15
  • Ok I have setup a spreadsheet you can use as well as a module to use to run the code. How can I upload it or send it to you so that you can access it? – art123456 Jul 22 '14 at 20:26
  • Just upload it in WikiSend or DropBox. – WGS Jul 22 '14 at 20:47
  • Here is the link to the dropbox file. Please read the comment in the beginning of the code. There is just one module. Thanks again for your help! https://www.dropbox.com/home/Coding – art123456 Jul 23 '14 at 12:17
  • @art123456: The link you provided redirects to a user's homepage (in this case, mine). Kindly use the public-facing link for the file. – WGS Jul 23 '14 at 16:32
  • Oops! I forgot I had to do that, I'm sorry. https://www.dropbox.com/s/3uxak1uip1x6es6/Test%20Module.xlsm Let me know if you have any problems. Thank you again for the help! – art123456 Jul 23 '14 at 18:31
  • It works for me without a hitch. I'm going to hazard two guesses. One, do you have any other workbook open while running `RunAll`? Two, you are not using Excel 2010, are you? – WGS Jul 23 '14 at 19:09
  • I do in fact have other workbooks open, but I always first click on the workbook I want, and then I run it. The other workbook nothing happens to it, I just wrote it in that one because it's where I write a lot of my macros to test them, etc. (I recently started using VBA so I wanted to keep them in one place for easy reference). I will try just using the workbook I sent you. Also, I am using Excel 2010, why does that matter? – art123456 Jul 23 '14 at 19:17
  • ALSO: Did you run the full program/read the comment at the top of the module? You do RunAll, and THEN MoveChart after it to move it back to cell N2. Did you do that as well? – art123456 Jul 23 '14 at 19:18
  • Yep, no problems there. Ran both macros apart first, no problem. Uncommented the `MoveChart` line in `RunAll` and ran without a hitch as well. I can record a video if you're up to it just to show it works. For the version, was just thinking if it's a problem with the reference library. Apparently not since we're using the same version. One thing: can you kindly try indenting the code properly per line in the `MoveChart` macro? It ran on my end without the indentation, but your side might be being picky. – WGS Jul 23 '14 at 20:40
  • Sure, I didn't know indenting it actually could cause problems (maybe it reads it as part of a different line or something). So I ran the macro using the book I sent you and it works fine. I also opened up another book and ran the macro on that with VBA open. So now it's working for some odd reason. I wonder why this is happening, because the difference now is that the module is alone rather than with all the other code I've written. – art123456 Jul 23 '14 at 20:50
  • And you don't need to record a video, that's fine, but putting it into a different workbook module made it work now on any workbook. Hmmm. Either way thanks for getting it to work haha. – art123456 Jul 23 '14 at 20:51
  • That has got to be very weird. Maybe there's a conflicting macro of sorts. Possible that you have a macro or action that moves the focus out of the workbook throwing the `MoveChart` macro or whatever. In any case, you really should bring down the character count on that code. But it's clean code for a somewhat beginner and that's all that matters for now. Good luck! – WGS Jul 23 '14 at 20:53
  • Thanks! And what do you mean by character count? Do you mean I do some things in a complicated way when it could easily be done in a simpler way? If so, I know, I'm just trying to first get a rough start of my macros and when I learn more I can edit them and make them cleaner (and I also need to comment a LOT of things so I don't forget what I did). – art123456 Jul 23 '14 at 20:58
  • I'm going to post code snippets in a while. You really should stop using `Select` in your code. It's unsafe and slow. See my [answer here](http://stackoverflow.com/questions/20738373/can-i-make-this-macro-more-efficient-or-faster/20754562#20754562) for some best practices and tips. – WGS Jul 23 '14 at 21:33
  • @art123456: See my edit above. I consolidated all your macros into one. Make sure you read the comments so you can get a gist of what is happening. I suggest putting breakpoints in the places you don't understand and studying them further. This is a massive reduction from 258 lines to 99 lines of code. Enjoy! – WGS Jul 23 '14 at 22:53
  • Wow, thank you so much, that's extremely helpful! If I have any questions, is there a better way to reach you on this site rather than commenting, or commenting back is fine? – art123456 Jul 24 '14 at 12:30
  • Either use chat or just post your question. There are many programmers out there in the `excel-vba` tag. – WGS Jul 24 '14 at 14:19