I have a problem with adding an event code to a newly created sheet.
The problem seems to only occur right after I open the Excel workbook.
I use
Dim codemod As Object
codemod = ActiveWorkbook.VBProject.VBComponents(Worksheets("Sheet4").CodeName).CodeModule
to add the code to the created sheet module but when I try to run this code right after opening the Excel workbook it gives me an error: run-time error '9' Subscript out of range. The debug points to the codemod line.
The weird part is that this error does not come up again when I change the code just a tiny bit and then change it back to the original state. After I do this the code runs as it should i.e. inserts code to the newly created sheet.
Anyone got any idea what may be the problem?
There is not much else to the code except inserting the lines but that does not seem to be the problem.
Thanks in advance
(This is my first action on S.O. so please don't shout at me when I'm doing things wrong.)
Did you concider preparing a workbook + sheet with the desired event code (Test1.xls-Sheet1). Then, in the target workbook (Test2.xls), copy that prepared sheet. The code in the target workbook would look like
Sub Demo1()
Workbooks.Open "Test1.xls"
Sheets("Sheet1").Copy After:=Workbooks("Test2.xls"). _
Sheets(Workbooks("Test2.xls").Worksheets.Count)
Workbooks("Test2.xls").Activate
End Sub
This obviously is a workaround but it works instantly.
A second option could be to prepare the 'workbook-with-one-sheet' and save it as a (sheet) template in D:\Documents and Settings\User\Application Data\Microsoft\Excel\XLSTART. In that case the code can be
Sub Demo2()
Sheets.Add Type:="Test1"
End Sub
Related
I made a workbook with several sheets for data entry, and I want the index/main sheet to display upon opening every time.
Everything on the internets says to use something like below, but I get a runtime error.
I've made sure the worksheet is named "Attendance Main" and the spelling is correct.
Most troubleshooting issues I've seen are about activating sheets for copying/pasting and other actions. I just want the main sheet to display each time the workbook is opened.
When I create a new workbook, with 2 basic sheets, the macro works. So I am wondering if other macros are interfering with it. However, none of my macros are in "ThisWorkbook", most are in their own modules.
Any help appreciated, and if you need any info from me to narrow down the issue I will try to provide what I can.
Private Sub Workbook_Open()
Worksheets("Attendance Main").Activate
End Sub
Run-time error '1004'
Activate method of Worksheet class failed
For me a simple select code inside the open event of Workbook works fine.
Private Sub Workbook_Open()
Sheets("ShowThisFirst").Select
End Sub
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!
I am attempting to copy different images to different worksheets of my Workbook using the following code below. I am changing the Target Worksheet Dynamically in a different sub, with a String Variable in the Global Declarations section. I can see the variable being passed to the sub and in fact it works the first pass through the code, but when I attempt to change the "TargetSheetIni" variable to a new sheet, it continues to use the first original sheet as it loops through.
Can you not change a target sheet after using the Set keyword? Should I refer to the sheet directly instead?
Sub Test1()
Dim TargetWS, SourceWS As Worksheet
Set TargetWS = Worksheets(TargetSheetIni)
Set SourceWS = Worksheets("Images")
DoEvents
SourceWS.Shapes(CurrentImageId).Copy
DoEvents
TargetWS.Paste Range(ColumnLetter2 & RwCnter)
DoEvents
End Sub
I think I may have figured it out. As far as I can tell the issue may be that I used the Copy Sheet Functionality in Excel when I originally created the target sheets. And even though I renamed the sheets both on the tab below and in the project editor... for some reason VBA kept targeting only the original sheet
I proved this by changing my code around to explicitly call the sheet I wanted to target like so:
ActiveWorkbook.Worksheets("Sheet2").Paste Range("I2")
And even doing that it would target sheet 1 for the paste command instead of the expected sheet 2. I deleted the three copy sheets and created a new one from scratch and re-executed code and now it targets sheet 2 as expected.
I found this article that sort of explains it I guess...
https://www.spreadsheetsmadeeasy.com/7-common-vba-mistakes-to-avoid/
Ok my last answer may have not been correct. It appears as though for some reason inserting an ws.activate caused my code to start workin.g
Very frustrating fix. as I have always heard to avoid using that.
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
Earlier this morning I asked my first question. Whilst investigating the suggestion put forward by Marco, I encountered a "does not make sense" situation. I went back to the immediately previous version of the macro suite to see what behaviour that gave. Let's call these Suite A and Suite B
In both Suite A and B there is the following code:
Public wsTemp As Worksheet
Sub DrillDown()
In Suite A there is the following:
Sub HandleNewFileNumber()
If iK <> 0 Then
wbTgt.Close
End If
Set wsTemp = ThisWorkbook.Sheets.Add(After:=Worksheets(1))
In Suite B there is:
Sub HandleNewFileNumber()
If iK <> 0 Then
wbTgt.Close
End If
Set wsTemp = ThisWorkbook.Sheets.Add(After:=Worksheets(1))
No, I have not simply copied the same code twice. I took each piece of code out of the two separate workbooks. The code is identical.
When I run the macro suite A everything runs through to successful completion. When I run macro suite B I get Error 1004. In both cases the Set of wsTemp is the first time wsTemp has been referenced.
I am at a loss to understand how the same code can give two radically different results.
Try
Set wsTemp = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Worksheets(1))
Or
With ThisWorkbook
Set wsTemp = .Sheets.Add(After:=.Worksheets(1))
End With
It's a very common problem: When you access an object from Excel (Sheet, Range, ...) and don't specify where it belongs to (eg a Worksheet belongs to a Workbook, a Range belongs to a Worksheet), VBA assumes you are referring to whatever is currently active (currently having the input focus).
If you write Worksheets(1), Excel will translate this to the first worksheet of the current active Workbook. When ThisWorkbook is not the active workbook, this will lead to the situation that you ask Excel to add a sheet to one workbook but put it after the sheet of another workbook - and that's not possible and will throw an error.
VBA beginners will often try to solve this by put activate-statements in the code, but that's the wrong attempt. There is no need to activate anything. Instead, just tell VBA exactly what you want. By writing ThisWorkbook.Worksheets(1), you specify that you mean the first sheet of ThisWorkbook (which is the WB where the code lives in). The second piece of code (using With) is just another way of writing it - but note that .Worksheet has a leading . that signals that we are accessing the sheet of the Workbook specified in the With-clause.
As a rule of thumb, never put anything in your code that let's VBA guess something.
Having spent an hour or two working through the entire suite of macros, applying the technique suggested by #Fun Thomas, and tidying up some other loose code as I went along, I can no longer reproduce the failure on my most up-to-date version of the macros.
Thank you everybody for your thoughts and suggestions. I will now concentrate on offering further diagnostic data to my very original post about flickering grey screens when opening workbooks.