Unexpected results from a Worksheet.Activate event - excel

I’m running excel 2010 on windows 7.
The following macro does what you would expect, ie (1) inserts a new worksheet, (2) adds a rectangle, and (3) activates cell A1.
Sub addSheetAndButton()
Dim buttonSheet As Worksheet
Set buttonSheet = ThisWorkbook.Sheets.Add
buttonSheet.Shapes.AddShape(msoShapeRectangle, 100, 100, 100, 50).Select
buttonSheet.Range("A1").Activate
End Sub
My problem is when I try to run it with a Worksheet.Activate event, for example:
Private Sub Worksheet_Activate()
Call addSheetAndButton
End Sub
This time (1) a new worksheet is not inserted, (2) the rectangle is added to the worksheet associated with the activate event, (3) cell A1 is not activated and (4) the rectangle remains activated.
What am I doing wrong? Any help would be greatly appreciated.

Thanks very much for trying this. I’m sorry it has taken me a while to get back, but I’ve been experimenting with this. I have discovered that when I exit and restart Excel, the addSheetAndButton macro works as expected under the Worksheet.Activate event. However, I have a different macro that uses another Worksheet.Activate event to update some charts. On what seemed to be a random basis, this would create a “run time error 6” - an overflow that resulted from trying to assign an out of bounds value to a variable.
I never got this error if I bypassed the Worksheet.Activate event/macro and ran the chart update macro by hand. After resetting VBA/Excel from the “run time error 6”, the addSheetAndButton macro behaved exactly as I described in my original post. The only way to cure it was to exit and restart Excel.
I think (hope) that I have traced the source of the run time error back to a line in my chart update macro where I had selected rather than activated a worksheet before reading data from it – though I am surprised at the result. It is worth pointing out that once Excel entered the “not as expected” state, the on-screen message from the following two lines was the name of the previous active sheet and not “Sheet1”.
Worksheets(“Sheet1”).Activate
Msgbox ActiveSheet.Name
Again, the only apparent way to cure this was to exit and restart Excel.
Thanks again for your help.

Related

How to Loop Through ActiveX Checkboxes on VBA

I'm actually trying to make a userform that controls every checkbox in the Workbook Sheets (it's mostly graphs that shows the data from a specific period for the Company), since every graph has the same checkboxes (ActiveX ones) with the same names on them I though about making a Userform that is always active and in this way the client can just select which ones he will use and it would just loop through the other sheets without a problem.
But here is the problem first of all my code:
Dim ws As Worksheet
If Me.CheckBox1.Value = True Then
For Each ws In ThisWorkbook.Worksheets
ws.OLEObjects("chkAno1").Object.Value = 1
Next ws
ElseIf Me.CheckBox1.Value = False Then
For Each ws In ThisWorkbook.Worksheets
ws.OLEObjects("chkAno1").Object.Value = 0
Next ws
End If
I did it with only one checkbox to test it out (There is a "chkAno1" in every sheet that I want to affect) but everytime I run the code and click the checkbox I get " Error 1004: The Method "OLEObjects" from object "_Worksheet" Failed", and what's weird is that If I change "ws" with "ActiveSheet" the code works fine, but only updates the currently open sheet.
So I'm at a loss right now.
thanks for your help. I found out the problem, there was some sheets without any Checkboxes on them, so the Code kept giving me the error.
The solution I found for it was to put On Error Resume Next at the beggining and it worked like a charm! (I actually needed to put it on the graphs as well)
But in the end I ended up reworking the code to affect directly the Graph using ws.ChartObjects("grafico").Chart.FullSeriesCollection(1).IsFiltered = True instead of ws.OLEObjects("chkAno1").Object.Value = 1 Because at the end the process of updating every checkbox and after that all the charts would be actually really slow on some older computers and updating directly the Graph showed a great increase in speed.
Thanks to everyone that Commented and I hope the solution I found can help someone else!

Excel crash after Copy and paste Chart image

I Need to Copy an picture/image of a chart which is in another workbook (WbO), and paste the picture in a worksheet in this workbook (TWb), using Excel vba.
I figured out a simple code to do this.
The good thing is that the code works. Stepping line by line throught the code everything completes perfectly.
However, if I run the code (no Stepping) it also runs until the end without any error and completes the job. BUT, by the end Excel Crashes without any error message, restarts and reopens the workbook. (all work lost).
The weirdiest thing is that it crashes 3 to 5 seconds after ending the run. 3 to 5 seconds is an enormous lenght of time for computing. What is it doing during this time??
For testing, I added a 'Msgbox "Completed", vbokonly' as last code line. This made vba stop and show the message, and no crash while the message is on screen. Clicking ok, the macro runs to the end and then, after some seconds ... Crash.
Searched for similar problems in the web and found some old posts refering errors related to copy/paste, but no complete crash like this.
Tried this same file/code in different PCs, both with up-to-date office 365 but different update channels (not same build). The result was exactly the same.
Tried changing the .CopyPicture statement to a normal Copy, and then using PasteSpecial as Picture. Same Result.
Even tried moving the copy/Paste instructions to different subs (suggestion from a 2018 post), and inserting DoEvents in between .. without any luck.
Does someone have a clue why this is hapenning?
How to overcome this issue?
Help welcomed
Sample code below:
Application.EnableEvents= False
Set WbO = /Workbooks.Open("WbOFileName",0)
Set ChrtObj= Worksheets("MyCharts").ChartObjects(1) 'Set handle to the Chart obj
TWb.Activate ' Activate destination Workbook = The Wb which contains the macro
ChrtObj.CopyPicture
RangeToPasteOn(1,1).Select ' Select Top-Left cell to paste the Chart on
ActiveSheet.paste ' Paste the Chart
' ... here Code to ajust Size and position to fit destination range
Application.CutCopyMode = False
Set ChartObj = Nothing 'Release handle
WbO.Close
Set WbO = Nothing
Application.EnableEvents= True

change cell colour when opening workbook

I would like to change the colour of two cells (C3:C4) to red every time my workbook is opened.
The code I have tried is in my Workbook_Open event but I'm getting Application-defined or object-defined error. Here is the code:
Private Sub Workbook_Open()
Worksheets("Balance Sheet").Range("C3:C4").Interior.Color = vbRed
End Sub
Is my syntax wrong or is it more that this can't be done during the workbook_open? And how can I correct it?
Ensure that your worksheet is called "Balance Sheet". Any typo would make Excel to not find and return an error.
As you wrote its not a typo.
So please check if makros are enabled in the excel file. In the default configuration makros are blocked and therefore nothing happens. Your code is working...
https://support.office.com/en-us/article/Enable-or-disable-macros-in-Office-files-12b036fd-d140-4e74-b45e-16fed1a7e5c6
Ah, it appears I was getting the error because I was trying to edit a locked sheet. Added lines to unlock and lock and it works fine.
Slightly embarrassing but lesson learned for next time.

Copy/Paste data to other existing workbook on timer

I currently have this VBA -
Sub StartTimer()
Application.OnTime Now + TimeValue("00:00:15"), "AutoCalc"
End Sub
Sub AutoCalc()
Application.CalculateFull
Sheets("Kine").Range("B603:E603").Copy _
Destination:=Workbooks("AutoImportAverages.xlsx").Worksheets("AvgKine").Range("B1:E1")
Application.OnTime Now + TimeValue("00:00:15"), "AutoCalc"
End Sub
The .OnTime command is working perfectly without the Copy/Paste section, which is great.
This gives me a list of values from an SQL query that will auto-update, as well as an average at the bottom of each column of values.
I'm trying to set this up so that the average will automatically be added onto columns in Minitab but I believe that the Macro is stopping the Auto-Update in Minitab.
So my idea is to copy-paste the averages into an Excel Workbook that has no macros of its own and then link that to Minitab.
Have I put in the Copy-Paste code wrong or is there some issue with where the macros need to be stored and how?
Quick Edit - I should add that current code gives "Run-Time Error 9, Subscript out of range" and highlights copy/paste code.
I've found the solution.
My destination workbook was open in a separate window so the source wasn't recognising it as being open. Bit of a nightmare!
It's necessary to have both workbooks open in the same instance of Excel.
Additionally, my original paste code only pasted "#REF". I have changed that to -
Workbooks("AutoImportAverages.xlsx").Worksheets("AvgKine").Range("B1:E1").PasteSpecial xlValues
Works much better.
One more thing, in case anybody might find it useful. The source workbook must be active in order to carry out the auto-update.
Adding below line sorted out most issues though its still a work in progress -
ThisWorkbook.Activate

Excel VBA forcing selection of objects after run

I've researched this to death and feel like I'm the only person it's ever happened to.
I have some VBA that:
Creates a copy of 3 sheets to a new wb
In the new wb converts to values, deletes objects (shapes and controls) and all but 3 ranges
Opens an existing third file and sets the contents of three ranges in that to match the new wb
Closes the existing file (saved)
Closes the new wb (saved)
Gives a message box saying complete
At the end of all this, something weird happens with the state of the windows. The selected cell does not appear selected. If I try and click a control afterwards, it selects the object (hence users could drag them). It shouldn't and this is the big problem.
I've tried selecting a cell through code, it throws an error. I had limited success by forcing drawing mode off using Call CommandBars("Drawing").Controls("Select Objects").Execute and activating a specific sheet & selecting a cell. However, even then if I even click on a few cells afterwards, the next time I select a control it will select it as an object rather than click the thing.
I have no idea why and can't find anyone who's seen this before.
Any ideas on what I can do?
Thanks,
Basil
I didn't figure it out entirely, but I did find a fix. Hopefully it works for anyone else who finds this problem.
At the end of the code I added this:
ActiveSheet.Shapes.Range("ctrlExportPrices").Select
ActiveSheet.Range("B8").Select
So it forced a control on the sheet to be selected, and then a cell.
The next time I select the control manually, it clicks it rather than selecting the drawing object.

Resources