My Excel project functions properly at home (with Excel 2010), but not on two work computers (with Excel 2016) and I suspect the Worksheet_Change event is the problem.
When the user makes changes, the yellow bar (in the screenshot) should turn white again, but it is not. I am getting 2 different responses on 2 work computers.
Two things to point out in the code:
In some places I use vbColor extensions, in others I had to use a numerical code.
One computer is not firing the Worksheet_Change event at all. I would note that the change event is at the top of the code, although that shouldn't have anything to do with it.
I'd appreciate advice and detailed explanations, to help me learn.
Private Sub Worksheet_Change(ByVal Target As Range) 'Check for On-Time and Delays then change the Command Button Colors to show completed.
'Return headers to white after jump to
Range("B3:I3,O3:V3,B28:I28,O28:V28,B53:I53,O53:V53,B78:I78,O78:V78,B103:I103,O103:V103,B128:I128,O128:V128,B153:I153,O153:V153").Interior.Color = vbWhite
'Check for On Time and Delayed Trips
'Trip 1 Scan Ready
If IsEmpty(Range("L3").Value) = False Then
If Range("L3").Value > Range("I3").Value Then 'If actual is greater than Departure
'If Delayed check for a delay code
If IsEmpty(Range("L24").Value) Then 'If Delay code is missing
Range("K24:L25").Interior.Color = 16711935
CommandButton1.BackColor = 16711935
CommandButton1.ForeColor = vbBlack
Else 'If Delay Code is present check for delay time
If IsEmpty(Range("L25").Value) Then
Range("K24:L25").Interior.Color.Index = 16711935
CommandButton1.BackColor = 16711935
CommandButton1.ForeColor = vbBlack
Else
CommandButton1.BackColor = vbRed
CommandButton1.ForeColor = vbWhite
Range("K24:L25").Interior.Color = vbWhite
End If
End If
Else
'Flight was on Time
CommandButton1.BackColor = 32768 '32768 = Green
CommandButton1.ForeColor = vbWhite
Range("K24:L25").Interior.Color = vbWhite
End If
End If
There could be a number of factors causing this problem. One way to diagnose is to troubleshoot like this:
At the beginning of your procedure, right after this line:
Private Sub Worksheet_Change(ByVal Target As Range)
...add a temporary line:
MsgBox "Changed: " & Target.Address
...then go change something in your worksheet (whatever change isn't firing the event as you'd expect).
One of two things will happen:
You'll have a message box pop up, showing the cell reference of whatever was just changed.
This demonstrates that the event is firing properly, so the issue must be in your code that follows.
Or, you won't get a message box pop up. This indicates the event is not firing, which could be caused by a few possibilities:
Are macros completely disabled in the workbook? This is often done automatically on workbooks received from outside sources. Save the workbook to a trusted location on the local computer or network (rather than opening from the email). Do other sections of code run properly? When you close/re-open the file, are you given a warning about Macro Security? Also, try rebooting the computer.
Other security settings could be an issue. Have you ever run VBA on these machines? You can confirm sure code is able to run in Excels' security settings in:
File→Options→Trust Center→Trust Center Settings→Macro Settings
As well as making sure macros are enabled there, you could also check Trusted Locations in the Trust Center, and either save your document in a listed location, or add a new location. Security settings will be "reduced" for documents saved in those locations.
Is EnableEvents being intentionally disabled elsewhere in your code? If you wrote all the code, you should know whether you set EnableEvents = False at some point. Perhaps it was intentional, but it's not being re-enabled.
Remember to remove the line you added temporarily, or that MsgBox will quickly get annoying by popping up every time a change is made. :)
You say "the change event is at the top of the code". A worksheet change event will only fire if you put the code in the sheet module concerned. If you've put the code concerned in a non sheet module (e.g. "Module 1" or similar, listed under the "Modules" branch in the object explorer) then that's the problem.
Also, you really shouldn't hard-code cell references like "L3" in your VBA code, because every hard reference will require amending should you (or a user) later insert rows/columns above/to the left of these references. Instead, assign meaningful named ranges to these cells back in Excel, and use those in your VBA.
Also, when using event handlers like you're doing, you should have something like If not intersect(Target, InputRange) is nothing then... so that the code only runs if something of interest changes.
I had the same problem.
I checked everything.
Everything seemed to be proper (enabled macros, EnableEvents=True, etc).
I closed and opened Excel.
Problem persisted.
There was nothing I could do.
I restarted Windows.
Problem disappeared.
Restart took 7 minutes (with all applications closing & restarting), trying to find the cause would take much more. Maybe I could have tried to find & kill every Excel process in Task Manager.
I don't like giving people the advice "try rebooting", but well, Windows is Windows.
I had a different problem. I had saved my worksheet under a new name and then added the code for the event. To get it to work, I had to close the worksheet and reopen it. It then showed the button to enable macros and the code started to work. Hope this helps someone.
Wade
I solved it simply deactivating "Design Mode" in the "Developer" tab.
It seems if you are in "Design Mode", this event (I don't know about others) won't work.
In 2019 Excel cut copy -> paste would not work the paste options were grayed out. Online sources said update and repair the app. I updated office and the copy/paste options worked.
However the worksheet_change event stopped working. After a lot debugging with no luck, I did a hail mary and commented out the subroutine and recreated it. It WORKED!! I have absolutely no idea why or how. If anyone has thoughts please share.
I had some code in a worksheet change that wasnt firing. I also had some code in Thisworkbook upon opening and saving. Resolved the issue by putting Application.EnableEvents = True at the end of the code for workbook open and workbook save.
Related
I have very simple code:
Private Sub Worksheet_Change(ByVal Target As Range)
Worksheets("PickList").Range("AN2:AN14").Copy Destination:=Worksheets("PickList").Range("AR2:AR14")
End Sub
I am simply moving some data from one column to the next. I'm running this code off of the PickList worksheet. I also have another worksheet, Config, that works together with PickList and depending on what was done in Config, some data may change in PickList.
Anyways if the code is put in PickList. I get the Range of Object error and shortly after it gives me the object invoked error and it crashes Excel 100% of the time. Now if I put this code in Config it works fine without error.
Now my thinking is that there is an issue with how my two worksheets work together. On Config there are some dropdowns that the user can select, and depending on how these dropdowns are selected, some data will change in PickList. I think the issue lies with me physically being on the Config worksheet while the Config sheet makes changes to the PickList which activates the Worksheet_Change function and maybe that is where the error stems from. But I am a novice and I'd like some advice on how to go about fixing this problem. Thanks in advance.
If you are looking for changes due to equations being updated, a Change_Event will not work. This will only trigger when a cell is physically changed.
-(Likely explanation of why this works fine on Config and not PickList)
You may need to re-work your logic to apply this. Run this code from Config. Determine what changes on Config will lead to changes on PickList. When this change is made on Config, then execute your worksheet change. You need to analyze your Target (changed cell)
Also, you need to disable Events before you make a change. Every time you make a change, you re-activate your macro (leading to an infinite loop and your instance of excel crashing).
Application.EnableEvents = False
'Physical changes to worksheet go here
Application.EnableEvents = True
I recently experimented with a macro that runs every time the active cell column changes:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cell As Integer
cell = ActiveCell.Column
Select Case cell
'code
End Select
End Sub
I quickly realized that this slows down Excel by a lot, so I turned the macro off. The problem is that it must have turned something on, because now every time I change the active cell in any Excel file on my computer, it loads a little bit, like if that macro was still running.
I deleted the macro, restarted the computer, but nothing.
If I manually turn off events (Application.EnableEvents = False), this problem goes away, but as soon as I open another Excel file (any file, not just the one I wrote the macro in), it turns back on.
What have I done and how do I turn it off?
The way you describe it, it seems that you have Saved the Worksheet_SelectionChange event to a personal.xlsb file.
Find it, delete the code and enjoy your Friday!
https://support.office.com/en-us/article/Copy-your-macros-to-a-Personal-Macro-Workbook-aa439b90-f836-4381-97f0-6e4c3f5ee566
I'm experiencing a strange issue occurring with my VBA Macros in Excel. Background is, I'm creating a template for Labour Logs to log hours that employees are on site. There is a main sheet where all the data is entered "Labour Log" and then 8 sheets, one for each of the days of the week and a Holidays sheet. There is a hidden sheet where my dynamic list and static lists are held.
The macros that are causing issues are the ones on the sheets for the days of the week. What they are doing is, searching the Labour Logs sheet for any cell with that day of the week in column B, then inserting that line on row 8 of the day sheet. This loops until all instances are entered. Example of Monday below.
Private Sub PullMondayData_Click()
Dim dc As Range
With Sheets("Labour Log") 'Reference to Labour Log Sheet
For Each dc In Intersect(.Range("B:B"), .UsedRange)
If dc.Value2 = "Monday" Then 'Search/Filter B:B for Monday
dc.Resize(1, 1).EntireRow.Copy 'Copy the row
Sheets("Monday").Rows(8).Insert Shift:=xlDown 'Insert in Row 8, shifting down
End If
Next
End With
Application.CutCopyMode = False 'Remove copy mode
End Sub
This usually works fine for Monday. I can usually hit that one multiple times without issue.
When I go back to the Labour Log sheet and change the day to any other day, I start getting errors on those sheets when hitting the macro. The macro codes is exactly the same, but with the relevant day entered in the correct spots.
The first error I usually get is:
Going to debug says error with this line:
I then stop the macro and run it again, getting the following error:
Debugging it gives this line:
After that, the only way I can close the Excel sheet is to end the process form the Task Manager, the rest of the program is locked.
From time to time, I also get a crash, and the output is this:
Problem signature:
Problem Event Name: APPCRASH
Application Name: EXCEL.EXE
Application Version: 16.0.6868.2060
Application Timestamp: 5723a711
Fault Module Name: mso20win32client.dll
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 57222bc3
Exception Code: c0000005
Exception Offset: 0008c78d
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 4105
Additional information about the problem:
LCID: 1033
skulcid: 1033
I've searched online for various answers, but they don't seem to work. I've tried the following:
Clearing the Excel folder in C:\Users\User_Name\AppData\Roaming\Microsoft\Excel
Cleaning the Registry
Changning the set printer (long shot, but saw a few people say it worked)
Running another day before Monday
Running Windows Update
Moving Application.CutCopyMode = False within the If loop
My knowledge of VBA isn't great and a lot of this code was taken from searches and altered to suit my purpose, but I don't understand why it is working for the Monday sheet, but crashes on all others.
Any insight would be much appreciated.
Thanks.
too little info to actually track that error down
but, assuming you're using a Userform with many buttons to click and have proper day processed, I'd propose you some code that can possibly help you keep things cleaner and, therefore, less prone to errors
set your buttons caption property as per the relevant day
so you'll have
PullMondayData button showing "Monday" caption on it
PullTuesdayData button showing "Tuesday" caption on it
and so on
have all your Pulldaybutton "Click" event handlers code just like follows:
Private Sub PullMondayData_Click()
PullDayData (Me.ActiveControl.Caption)
End Sub
Private Sub PullTuesdayData_Click()
PullDayData (Me.ActiveControl.Caption)
End Sub
and so on
add the following sub to your Userform code pane
Private Sub PullDayData(thisDay As String)
Dim dc As Range
With Sheets("Labour Log") 'Reference to Labour Log Sheet
For Each dc In Intersect(.Range("B:B"), .UsedRange)
If dc.Value2 = thisDay Then 'Search/Filter B:B for Monday
With Sheets(thisDay).Rows(8)
.Insert Shift:=xlDown 'Insert in Row 8, shifting down
.Value = dc.Resize(1, 1).EntireRow.Value
End With
End If
Next
End With
End Sub
all what above can still greatly improved, but it'll give you at least the following benefits:
write much less code
and thus both make much less effort in maintaining it and possibly have many few errors!
not make use of copy/paste methods to both not passing through clipboard and be faster
For further effective improvements I'd suggest you the following steps:
use AutoFilter() and SpecialCells() methods of Range object to improve both control and efficency
use classes
While I agree with user3598756 that this isn't enough to give an answer with certainty, I do have some additional things to try:
I've had much better results using .CurrentRegion, than .UsedRange to get the area of data. There are exceptions, but if you have headers that can't be blank and at least one column with no blanks, it works flawlessly.
When you have more than one thing on a line causing an error, breaking it out will give you better info about crashes, so change: dc.Resize(1, 1).EntireRow.Copy into two statements: dc.Resize(1,1) and dc.EntireRow.Copy.
COM objects, and Range objects like .Rows(x) in particular, are tricky beasts. This seems to be worse in C# addons than VBA macros, but I've often seen them not update as expected when you do something to major their contents. The work around is the general case of the specific case I gave in point 2: one dot good, two dots bad. For example instead of calling Sheets("Monday").Rows(8).Insert try something like:
Dim MondaySheetRow as Range
MondaySheetRow = Sheets("Monday").Rows(8)
MondaySheetRow.Insert Shift:=xlDown
Lastly I've made a habit of not updating sheets that aren't active. Instead I activate the sheet I'm going to make changes to, make the changes, then return to the originally active sheet. This mimics the way a user would manually make the changes which also helps visually show where the macro went in the calls leading up to an error.
I have a private subroutine in Workbook A that is running any time I open or close and save other unrelated workbooks. I'm trying to understand why that occurs so I can capture all potential errors that may occur.
The subroutine is an ActiveX ComboBox named TabProg that is supposed to run when the value is changed. I have currently added in a check to see if the active sheet trying to run the code is the "Program Loading" sheet to try and divert any potential errors. See snippet below.
Private Sub TabProg_Change()
MsgBox "Whomp!", vbOKOnly + vbExclamation
If ActiveSheet.Name <> "Program Loading" Then 'do nothing
Else
'Run desired actions on "Program Loading" sheet
End If
End Sub
Any known reasons why this is occurring or other ways to catch it would be helpful. Thanks!
Edit 1: I do not see this problem occur when I open other workbooks in new instances of Excel.
Edit 2: I have modified the code to include a message box whenever the code tries to run, now shown above. It is occurring every time I open or close and save any Excel file, including the file itself. The drop down list in the ActiveX ComboBox is a list of names that correspond to 10 sheets within Workbook A. If I delete the sheet that ComboBox is currently set to, the error will disappear. If I change the ComboBox to a different sheet, the error will reappear.
From what you've wrote in your question, I don't think that your problem can be replicated. I think that your Excel file got corrupted. I had an experience like this: had a file for experimenting with macros, one of the macros used Excel Speech object to say "This is a test file" on opening that particular file. The macro was (as all other macros from this file) not part of my PERSONAL workbook, it was assigned to ThisWorkbook in the bespoke file. At some point a funny thing happened: this "This is a test file" private subroutine got activated every time I opened any Excel file. I did not find any solutions, I just deleted the file where the subroutine was stored. This resolved the problem, but I have no explanation for this. I am afraid the same thing may apply to your file, but maybe other folks have a better idea... maybe it's something in the system registry??? I don't know. Can you manually copy elements / code from this file to a newly created file and just delete the original?
Seems there is some bug. Can't resolve this problem, all code is running fine and I am able to see the AutoShape is getting copied from Excel file but it is not adding it to PowerPoint. Popping up an error Run-time error '-2147188160(80048240) View.Pastespecial : Invalid Request. The specified data type is unavailable
If Range("H" & i).Value = 1 And Range("B" & i).Value = "FRONT" Then
objPPT.Presentations(1).Slides(9).Select
objPPT.ActiveWindow.View.PasteSpecial DataType:=ppPasteEnhancedMetafile
Your code will be faster and possibly more reliable if you don't rely on selecting anything:
With objPPT.Slides(9).Shapes
Set objShape = .PasteSpecial(ppPasteEnhancedMetafile)(1)
With objShape
' set coordinates and such here
End With
End With
As to why you're getting the error message, try stopping the code after you've put something on the clipbard. Then switch to PowerPoint, use Paste Special to see what paste options are available. If EMF isn't one of them, that's your problem ... you're not putting anything in EMF format on the clipboard.
I had a similar issue, but I found a different solution; it may be specific to what I was doing though.
I setup a program where I would:
(manual) Copy an entire webpage that was a report on several performance metrics
(manual) Pasted it in to excel
Run the program to extract the values I want and then clear contents of the sheet I pasted them on.
Eventually after many tests, it would fail with this same automation error when I tried to access the sheet:
Sheets("PDX Paste").Activate
I was able to activate every other sheet except that particular one, even using the index value instead of the direct name reference. After googling to no success I found out that the copy and paste from the website was also pasting invisible controls. When I found this out I had 1,300+ shapes when I only expected 1 (the button I use to trigger the program). It was actually only apparent when a glitch - presumably due to so much memory being used to store these controls - displayed for a few seconds.
I ran the following code independently and then appended it to the end of my program when I do the cleanup of the data. The code goes through the sheet and deletes any shape that isn't the same type as my button. It would have to be adapted if the shapes you want to delete are the same type as the shapes you want to keep. It also becomes simpler if you don't have any shapes to keep.
Dim wsh As Worksheet
Set wsh = ActiveSheet
Dim i As Integer
For i = wsh.Shapes.Count To 1 Step -1
If wsh.Shapes(i).Type <> wsh.Shapes("UpdateDataButton").Type Then
wsh.Shapes(i).Delete
End If
Next i
I'm not sure this would solve this problem, but hopefully this can help others and prevent loss of time figuring out what may be causing this relatively vague error message.