+ Reply to Thread
Results 1 to 19 of 19

Functional VBA code errors out when included in Worksheet.Change event

  1. #1
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Functional VBA code errors out when included in Worksheet.Change event

    First time posting a question – before that, I would like to say thank you to this group for their past work – I’ve found several solutions / guidance that led me to solutions over the last year.

    Here the problem that has me stumped. I have a Worksheet.Change event that triggers two worksheets to be sorted via a Do until loop which works fine. I want to add code to copy a formula to a column range – basically reset those cells where I have overwritten the formula through manual input. The code works fine when it’s included in a standard module, but when the same code is included in a Worksheet.Change event, the first pass though the loop works fine (on Sheet1), but on the second pass (Sheet2) I get a Run-time error: 1004 - Select method of Range class failed on this line of code:

    Range("N4", Range(endcell).Offset(0, 13)).Select

    Here's the full code:

    Please Login or Register  to view this content.
    I’m mystified how this code can work fine in a normal module, and even work once in a Worksheet. Change event, but error-out on the second pass. Hopefully this is something obvious related to the differences between the two, but I’m stumped. I’ve searched on the internet, but have had no luck. The attached workbook was created to test whether there was some corruption in the original workbook causing the problem, but it behaved the same way. If you first run the macro using the button, the formula in Sheet1, A1 will be copied to the yellow highlighted cells. If you then reopen the workbook (just to reset / clear everything), then change the value in Sheet1 A29 you’ll see that the yellow highlight is completed on Sheet1 and then you will get the runtime error. . Appreciate any suggestions. Aquxiano
    Attached Files Attached Files

  2. #2
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Not sure why you would want a change event handler on one sheet to put a formula from the first sheet into a range on another sheet.

    Given that the event handler is running on Sheet1, it's a little redundant to set a variable equal to Sheet1 and then select the sheet. It's already active.

    I think you need to take a step back and think through the steps you need to take. Avoid selecting sheets and cells.

    I guess you're trying to avoid sharing sensitive information but, the more realistic your sample workbook is, the more sense it will make to others and the more chance you will get a practical solution.

    Better to explain the process you are trying to follow rather than provide code that doesn't work.

    Regards, TMS
    Trevor Shuttleworth - Retired Excel/VBA Consultant

    I dream of a better world where chickens can cross the road without having their motives questioned

    'Being unapologetic means never having to say you're sorry' John Cooper Clarke


  3. #3
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Thank you for your reply.
    - The formula is exactly the same on both sheets, I could duplicate it on sheet2, but since its exactly the same, I didn't figure I needed to - not sure I see the advantage unless that's the reason the code fails.
    - Regarding setting the variable to sheet1, it is redundant on the first pass, but necessary for the second pass because the variable becomes sheet2 (if there's a better way to change the variable for the second pass - I don't know what it is
    - What is preferable to selecting sheets/cells?
    Since I didn't explain it clearly the first time, let me take another stab at it. What I'm trying to do is create a worksheet.change event that triggers when the date on one worksheet is changed and will copy a formula to a range on two different sheets
    - I excerpted the problem code because I though it would just muddy the water to include the original workbook with a lot of other code - which also includes the code that doesn't work. Would that type of detail be helpful?

  4. #4
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Well, the formula
    Formula: copy to clipboard
    Please Login or Register  to view this content.
    clearly isn't t the real formula. And, although this still demonstrates the problem, knowing what the real formula is might make a difference in providing an alternative solution.

    I'll look again tomorrow.

    Regards, TMS

  5. #5
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    True, but I didn’t figure that one formula vs. another would be the cause. My assumption, my mistake. Attached is my file. Note that Sheets “Do Anything Very Easy” and “DAVE-Bear Flags” are both first sorted by Column K, then by Column G. The hyperlink in Column G does this sort. On the “Do Anything Very Easy” sheet, when you change the date in cell R1, both sheets are resorted alphabetically. Before you do this, note the closing price on line 5 is $9,999.00. This isn’t a real price, but an example of manually overwriting the existing Index/Match formula. I’ve left the problem code live so when you change the date you will get the error previously described. The error occurs while trying to update the bear flag page (note that TXP now shows the closing price of $78.53 as a result of the formula being copied over the manual entry.
    I’ve highlighted the offending code between two rows of asterisks in the Worksheet.Change code toward the end. If you want to comment this out, you can switch between sorting by Columns A, G, or J by clicking on the respective column headings/hyperlinks. Sorry for the confusion, I was trying to make the question simple, but like I said this is my first question, so I learned something new.
    Attached Files Attached Files

  6. #6
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    I suspect the problem, in the test code, is going to be this:

    Please Login or Register  to view this content.
    There's no guarantee what the active cell will be either in the first run, or subsequent runs.

  7. #7
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    I’m confused. You wanted to see the actual code because that might make a difference in suggesting a solution, then after it’s provided you use the test file code to make a suggestion?
    Using endcell = activecell.address in the test code only demonstrates the range dynamic. The actual code anticipates the problem you raise by using this code

    ActiveSheet.Columns("A:A").Select
    Selection.Find(What:="~?", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
    endcell = ActiveCell.Offset(-1, 0).Address

    So it finds the first row with a question mark in column A and then goes to the previous row using Offset – always going to the last row of data. Notice that this same code is used and works except when I try and copy the formula using these three additional lines.
    Range("I_Mformula").Copy
    Range("N4", Range(endcell).Offset(0, 13)).Select
    Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False

    Thanks for your effort though. I do appreciate it.
    Last edited by aquixano; 09-19-2015 at 03:42 PM. Reason: sounded to abrupt on rereading

  8. #8
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    You wanted to see the actual code because that might make a difference in suggesting a solution, then after it’s provided you use the test file code to make a suggestion?
    Good assessment . Problem being that I struggled to work out what the "real" code was doing. There's a lot of it. So I just reverted to looking at the test code.

    Looking at the example above, you could change this:

    Please Login or Register  to view this content.
    To this:

    Please Login or Register  to view this content.

    Regards, TMS
    Last edited by TMS; 09-19-2015 at 06:24 PM. Reason: Add Tilda (~) in Match statement

  9. #9
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Here's an example workbook with some test subroutines including an event handler.

    Regards, TMS


    Please Login or Register  to view this content.
    Attached Files Attached Files

  10. #10
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Thanks for your effort and the sample code. Yes, there is a lot of code in the real workbook – primarily navigational – jumps me to the next cell requiring info past those cells with formula or changing cell colors to highlight different conditions I want brought to my attention. Your code:

    Range("N4", Range(endcell).Offset(, 13)).Formula = Range("A1").Formula

    Is a slick way of “copying” a formula – I didn’t realize you could do that – I’m assuming this will retain the relative/absolute nature of the source formula correct? In the past when “resetting” a formula I’ve set the target formula using this code:

    ActiveCell.Offset(3, 3).Value = "=ABS(Target-I42)*100"

    But in the current instance I needed the formulas to be relative I didn’t know if that was possible when in essence I was hard coding the formula into VBA. Thanks for the tip.
    You’ve got a couple commands I’m not familiar with so I need to research to understand how your code works to see if I can incorporate it. Thanks again for the help.

  11. #11
    Forum Expert mikerickson's Avatar
    Join Date
    03-30-2007
    Location
    Davis CA
    MS-Off Ver
    Excel 2011
    Posts
    6,229

    Re: Functional VBA code errors out when included in Worksheet.Change event

    There is nothing in the OP code that requires Selecting.

    Remove the selection and fully qualify the references, that should fix almost everything.

    The one curiosity that I see is the named range I_Mformula. Is that scoped to the workbook level or is it a worksheet level name?
    _
    ...How to Cross-post politely...
    ..Wrap code by selecting the code and clicking the # or read this. Thank you.

  12. #12
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    @mikerickson: no argument. The point of the first example, the OP's code modified, was to demonstrate a simpler way of copying the formula. I wouldn't choose to select a sheet or a range, but the OP did. The comment highlights the fact that the column is left selected. The second example shows a way to locate the row of the first question mark and use that row number in the range address. And, again, not using Copy and Paste to load the formula.

    @aquixano: the sample workbook demonstrates copying a formula in cell A1, named "TheFormula". In cell A, the formula is a simple
    Formula: copy to clipboard
    Please Login or Register  to view this content.
    . In N4, that's exactly what you get. In N5, and subsequent rows, the formula is adjusted just as if you dragged it down.

    Have you looked at the example? Did you test the code? If not, perhaps you need to give it a go.


    Regards, TMS

  13. #13
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    @TMS – I did look at your sample workbook briefly last night, but it didn’t work the first try and I had to finish some other stuff before today so I tabled it. Tried it this morning and it worked fine – I bet that my EnableEvents had been turned off during a failed VBA run and I didn’t check to turn it back on. I see now the VBA generates relative addresses. I’ll spend more time with your code today.

    @TMS/mikerickson – “OP code?” – Operator Code?
    I thought fully qualifying reference meant avoiding things like “Activesheet” or “Thisworkbook” using actual references for everything. Pardon my ignorance, but I don’t understand how that is an alternative for selection. Can you give me a 5cent example or refer me to some where I can read up. I did search the internet trying to learn this myself, but am not confident I found the right context for your point.

    @ mikerickson – I_Mformula is defined at the workbook level. I did it that way so that I could copy it to both worksheets. (Honestly I’m not sure if that make a difference, but in my past experience I’ve found it better to define at a workbook level.) Originally when I started using a lot of range names I thought it make more sense to define at a worksheet level generally, but subsequently had to redefine them at a workbook level as my code evolved. That’s only one instance, but it was a pain to redefine 50-60 range names to a workbook level so, now I generally default to the workbook level. Do you have a default preference for defining range names?

    Thanks for your input,
    aquixano

  14. #14
    Valued Forum Contributor
    Join Date
    03-24-2014
    Location
    England
    MS-Off Ver
    Excel 2003 - 2016
    Posts
    575

    Re: Functional VBA code errors out when included in Worksheet.Change event

    "OP" = Original Post. ie, your first post.

  15. #15
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Or, referring to you as the Original Poster ... as, for example, the OP said, "..."

  16. #16
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    @BellyGas/TMS - Thanks.

  17. #17
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    ThisWorkbook always refers to the workbook running the code, so it is fairly safe. ActiveWorkbook and ActiveSheet refer to, well, the active workbook and worksheet. However, this can change and may not be what you expect it to be, depending on what your code does. Adding a workbook or worksheet will make it active but it's not always easy to keep track. Always better to define object variables and assign them so that you can refer to the objects with confidence. Fully qualified means specifically referring to the workbook, the worksheet, the range and the specific property of the range. So, ThisWorkbook.Sheets("Sheet1").Range("A1").Value.

    Note that you do NOT need to select anything to make changes to it.

  18. #18
    Forum Contributor
    Join Date
    09-21-2014
    Location
    Midwest USA
    MS-Off Ver
    2010
    Posts
    349

    Re: Functional VBA code errors out when included in Worksheet.Change event

    Thanks TMS - always good to improve skills. I know that in a dynamic situation I can use the offset property from a named range to change another cell - I'm thinking of reasons I've used Select in the past. I know I've had situations in the past when a piece of code wouldn't work until I Selected the range -don't remember a specific example to cite, but from what's been said already there must be a different resolution rather than using Select property. I'll try and avoid using Select in the future and post a question the next time I can't resolve an issue without using Select. Is the "Activate" property also to be avoided like Select?

  19. #19
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    44,918

    Re: Functional VBA code errors out when included in Worksheet.Change event

    To see the difference between Select and Activate, observe the output in the Immediate Window. But, to answer the question, yes, avoid.

    Please Login or Register  to view this content.

    In terminology, Select is a Method, as is Delete, etc. Properties are things like Value, Formula, Font, Hidden, etc.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Automatically add worksheet change event code
    By kl_clifford in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 08-13-2015, 03:28 PM
  2. Worksheet change event code
    By Nitefox in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 01-18-2014, 10:52 PM
  3. Code for Worksheet Change Event Needed
    By ARGK in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 06-17-2013, 11:54 PM
  4. Worksheet Change Event code help
    By kev_33 in forum Excel Programming / VBA / Macros
    Replies: 12
    Last Post: 03-12-2013, 01:51 AM
  5. worksheet change event - my code isnt working
    By tinkerbelle in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 06-17-2010, 06:58 AM
  6. Code for button errors due to worksheet name change
    By ge0rge in forum Excel Programming / VBA / Macros
    Replies: 9
    Last Post: 10-15-2008, 12:22 PM
  7. [SOLVED] Worksheet Change event code moved to Worksheet Calculate event... and it's not working
    By KimberlyC in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 06-23-2005, 06:05 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1