+ Reply to Thread
Results 1 to 28 of 28

UDF to capture change in cell values

Hybrid View

  1. #1
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    UDF to capture change in cell values

    I have created a UDF to display "Success" (to keep this simple) every time one of the cells in the range D1:D4 changes.

    However, 3 out of 4 of the cells contain real-time data that is refreshed every 1500 milli-secs and so every time the cells refresh the function triggers the MsgBox to display even though the values haven't changed. I only want the MsgBox to display if the values in those cells change.... can anyone help, I have spent the last 3 days trolling the net for a resolution but to no avail?

    =Trigger(D1:D4)

    Function Trigger (theParameter As Variant)
          MsgBox "Success"
    End Function
    Appreciation in advance.

  2. #2
    Registered User
    Join Date
    11-10-2011
    Location
    Summit County, CO, USA
    MS-Off Ver
    Excel 2007
    Posts
    4

    Re: UDF to capture change in cell values

    I can't reproduce the problem, at least in Excel 2007. Every time i enter the same data in one of the D1:D4 cells I get no response, but if I enter something different, the "success" msg appears. How do you do your 1.5 sec refresh?

  3. #3
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    I'm using a third party add-in that provides the real-time data and the setting on the refresh is 1500 millisecs. It's definitiely the real time data because if I remove the input from the function cell for these 3 cells the function works only when I go in manually and change the value of the fourth cell.

  4. #4
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: UDF to capture change in cell values

    You could cache them locally:

    Option Explicit
    
    Dim dic As Object
    
    Function Trigger(r As Range)
        Dim cell As Range
        Dim sAdr As String
        
        If dic Is Nothing Then Set dic = CreateObject("Scripting.Dictionary")
        
        With dic
            For Each cell In r
                sAdr = cell.Address(External:=True)
                If .Exists(sAdr) Then
                    If cell.Value <> .Item(sAdr) Then
                        MsgBox sAdr
                        .Item(sAdr) = cell.Value
                    End If
                Else
                    .Add Key:=sAdr, Item:=cell.Value
                End If
            Next cell
        End With
    End Function
    If you used a lot of these, you'd bring the workbook to its knees.
    Last edited by shg; 11-18-2011 at 07:28 PM.
    Entia non sunt multiplicanda sine necessitate

  5. #5
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    I would use hundreds of these and I need to avoid resource strain on the workbook. Thanks for the input though. I am seeking a way to disregard the data refresh thats triggering the function and just trigger on change in values.

  6. #6
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    Try putting "Application.Volatile False" as the first line in your UDF().
    Volatile UDF()s are executed every time the sheet calculates.

    Another solution would be to have the UDF() check all the values with a copy of the values somewhere else in the workbook and if they are different then put the message up and copy the values to the copy of the values for the next refresh.
    Foxguy

    Remember to mark your questions [Solved] and rate the answer(s)
    Forum Rules are Here

  7. #7
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    Thanks for responding, I've tried Application.Volatile (false) but it didn't work and I can't cache or copy the data elsewhere to compare the changes because I need the function to work across many rows and data will be changing on different rows periodically so it will always be different.

    Any other suggestions?

  8. #8
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    I don't think you put "()" around the work "False" in the volatile statement.
    Put "()" around the parameters when you want to return a value.

    I don't understand why you can't make a copy of the data.
    I also don't understand why it's a problem that the data is always different. Isn't that what you're looking for?

    Just so were are on the same page.

    Function Trigger (theParameter As Variant)
        Dim rCopy as Range
        Dim lRow as Long, lCol as Long
    
        set rCopy = <the copy of data>
    
        With theParameter 
            For lRow = 1 to .Rows.Count  
                For lCol = 1 to .Columns.Count
                    If .Cells(lRow, lCol).Value <> rCopy.Cells(lRow, lColl).Value Then
                        MsgBox "Success"
                        .Copy rCopy
                        Exit Sub
                    Endif
                Next lCol
            Next lRow
        End With
    End Function

  9. #9
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Exclamation Re: UDF to capture change in cell values

    Maybe I didn't explain the scenario as clearly as I could have, hopefully this helps.

    I will have the same function name on each row that will read in four fields of data on the corresponding row if any of the values change. Ie. =Trigger (D3:G3), =Trigger(D4:G4), =Trigger(D5:G5), etc.

    http://www.designcymru.com/images/example.jpg

    If a field on row 3 changes the function will pull in the values of those fields for me to do something specific with them. If I copy the values from row 3 to compare them next time I get a change and then a value in row 5 changes it will pull in a seperate set of data and of course it will be different. If I somehow store the data by each line to compare against the next time it will be very resource intensive on the workbook given I need this function to cover 1000+ lines.

    I tried Application.Volatile (False) as one of the first solutions but this doesn't work with the real time data refreshing in these cells every 1500 millisecs. This is my real issue, initiating the function on a row when one of the correspinding cells it's watching on that row actually changes value.... instead of the functon triggering across 1000 rows every 1500 millisecs.

    Hope this helps...

  10. #10
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    What you're saying is that you only want to trigger a UDF() if a value actually changes to a different value, not if it changes to the same value.

    I've never heard of a way to tell Excel to not trigger a UDF() if the new value is the same as the old value. As far as I know you have to store the old value and compare the new value to the old value.

    The UDF() could be made faster by having it trigger just once for the entire 1000 rows and keep the old values in memory instead of on a worksheet. So at least it doesn't take the time to save the values to disk.

    Sub Trigger(ByVal r as Range)
        Static aOldValues
        Dim aNewValues
        Dim lRow as Long, lCol as Long
    
        If uBound(aOldValues,1) <= 0 Then
            aOldValues = r.Value
        Else
            aNewValues = r.Value
            For lRow = 1 to r.Rows.Count
                For lCol = 1 to r.Columns.Count
                    If aNewValues(lRow, lCol) <> aOldValues(lRow, lCol) Then
                        MsgBox "Success"
                        aOldValues = aNewValues
                        Exit Sub
                    End If
                Next lCol
            Nes lRow
        End If
    End Sub
    Last edited by foxguy; 11-18-2011 at 11:25 PM.

  11. #11
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Thumbs up Re: UDF to capture change in cell values

    Thanks for this foxguy, I've been looking at this all morning but it seems it's not populating the array correctly.I had 2 cols of values for 50 rows and then the function in the 3rd col. It returned the time nicely and updated every time I manually changed a value but I couldn't get it further than initializing the array to test comparing the values.

    I placed a break at Trigger = vArr to see how the array was populating in the Locals window and this is what it looked like:
    Screenshot of Locals window
    Also, is the code to compare rCells2Check values versus corresponding values in the array accurate?
    Function Trigger(ByVal rCells2Check As Range) As Date
    
        Application.Volatile False
        
        If rCells2Check.Rows.Count > 1 Then
            MsgBox "This Function Will Only Work On 1 Row"
            Exit Function
        End If
    
        'create variable that will will hold values between triggers
        Static vArr As Variant
    
        Dim Index As Integer
        Dim YesNo As String
        Dim Price As Double
        Dim lCols As Long
        Dim lCol As Long
    
        'Tell VBA where to go if an error occurrs
        On Error GoTo EF
    
        'Turn off features that slow things down
        With Application
            .EnableEvents = False
            .ScreenUpdating = False
        End With
    
        'Ignore next error
        On Error Resume Next
        'check to see if the array exists
        lCols = UBound(vArr, 1)
        'reset On Error
        On Error GoTo EF
    
        'Assign row number as unique index number and YesNo and Price values from range
        Index = rCells2Check.Row
        YesNo = rCells2Check(1).Value
        Price = rCells2Check(2).Value
    
        If lCols <> rCells2Check.Columns.Count Then
            'either vArr has not been initialized
            'or the user has changed the # of columns to check
    
            ReDim vArr(1 To 1, 1 To 1)
            'just create a blank array to get things started
        End If
        
        If UBound(vArr, 2) < Index Then
            'add a new column to array if this data row has not been created yet
            ReDim Preserve vArr(1 To lCols, 1 To Index)
            'put the values from rCells2Check into the correct column in array
            For lCol = 1 To lCols
                vArr(lCol, Index) = rCells2Check.Columns(lCol).Value
            Next
            'Trigger = vArr
        Else
            'vArr was already initilized so check values
                If rCells2Check.Columns(lCol).Value <> vArr(lCol, Index) Then
                    MsgBox "Value in one of the cells has changed"
                End If
        End If
        
    EF:
        'Turn Features back on
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    
        'return the data & time to put into the cell with "=Trigger(.....)" in it.
        Trigger = Now
    End Function

  12. #12
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    "Trigger = vArr" was commented out. I left your code in the macro so you could compare your code with code that works (hopefully).
    "Trigger = vArr" is trying to put an array into a Date variable for the Function to return. That will always crash with a "invalid type" (or something similar) error.

    Didn't catch a bug in my macro

        If lCols <> rCells2Check.Columns.Count Then
            'either vArr has not been initialized
            'or the user has changed the # of columns to check
    
            ReDim vArr(1 To 1, 1 To 1)
            'just create a blank array to get things started
        End If
     
    should be
    
      
        If lCols <> rCells2Check.Columns.Count Then
            'either vArr has not been initialized
            'or the user has changed the # of columns to check
    
            lCols = rCells2Check.Columns.Count        
            ReDim vArr(1 To lCols, 1 To 1)
            'just create a blank array to get things started
        End If
    The old code was always reinitializing the entire array every time (which erases all the data in it).

    I don't see any point to these lines:
        YesNo = rCells2Check(1).Value
        Price = rCells2Check(2).Value
    You never use them anywhere.


    You comparison looks fine. I would put into the message the address of the cell that triggered it, so the user could easily find the change.

  13. #13
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    Thanks foxguy. YesNo/Price are values I want to use when I get the msgbox displaying if values are different, getting a little ahead of myself there.

    I created cellChanged = rCells2Check.Cells.Address to include in the msgbox.

    I've tested the sheet and the array populates with the right # of cols perfectly, then when I change a value it takes the right route through the Else below but doesn't compare the values at all. I've spent some time looking at this but it seems this code should work. Am I missing something?

        
    Else
        'vArr was already initilized so check values
           If rCells2Check.Columns(lCol).Value <> vArr(lCol, Index) Then
                   MsgBox "Value in " & changedCell & " has changed"
           End If
    End If

    Also, it seems the function sometimes reads in NA/Empty values and then the actual values if a cell value changes. I've read this is common so I was planning on adding the following code to check each value in range separately and exit if this is the case right off the bat. Is this the most efficient way to do this?

    If IsEmpty(rCells2Check(1).Value) Or IsEmpty(rCells2Check(2).Value) Then
        Exit Function
    End If

  14. #14
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    Quote Originally Posted by chris1983 View Post
    If IsEmpty(rCells2Check(1).Value) Or IsEmpty(rCells2Check(2).Value) Then
        Exit Function
    End If
    What if only 1 of the cells in Cess2Check will be N/A. Do you want the values in the rest of cells to be available for the next comparison.

    I didn't look at the entire macro. I just looked at the comparison code. I didn't even notice that you weren't cycling through the cells.
    I also failed to notice that you're not putting the new value into the array for the next change to check against.

    I'm writing this on the website. I'm not testing this, so if there is a typo or oversight, I hope you catch it.

        
    Else
        'vArr was already initilized so check values
        For lCol = 1 to lCols
           set r = rCells2Check.Columns(lCol)
           If (r.value = vbError) or (IsEmpty(r.Value) Then
               'skip this one
           ElseIf r.Value <> vArr(lCol, Index) Then
               cellChanged = r.Address
               vArr(lCol, Index) = r.Value
               MsgBox "Value in " & changedCell & " has changed"
           End If
        Nex lCol
    End If

  15. #15
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    Thank you so much foxguy for all your help on this. You're right I would need to update the one valid value if one of the values in the range was NA/Empty, what's the easiest method of doing this? I also thought if I checked these values right at the start of the function and they are both NA/Empty I could exit right away to save time given I need this function to work across 1,000 rows. Or wouldn't I notice a time difference? Minimal latency on updates is critical for me given the potential to expand rows further than 1,000...

  16. #16
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,998

    Re: UDF to capture change in cell values

    Have you tried using the ID property of the cells? In the function, iterate each cell and test value against ID; if different, update the ID and process; if not, do nothing.
    Everyone who confuses correlation and causation ends up dead.

  17. #17
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    I never new there was an Cell.ID property. You learn something new every day.

    Chris;
    This sounds promising. Use the ID property instead of an array in the UDF(). I can't imagine that it's enough faster to make a difference, but it looks like it would be much easier to understand and program.

    In fact I think I'm going to look into using it in all my workbooks. It would make it easy to Undo changes I don't want to allow.

  18. #18
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    Thanks for the ideas foxguy, this is the for the long term so it'll be worth investigating. If I compared the full 500 lines once versus each line 500 times how would I identify the row that changed, I've put some thought around what that code might look like but I'm just not getting it.

    I still see the function pulling in NA values so this code doesn't seem to be working and this is a critical piece. It seems to continue through to the ElseIf statement and display the msgbox even with one of the cells in the range having an NA value, so I'm assuming what I have below is inaccurate?
    If (r.value = vbError) or (IsEmpty(r.Value) Then
         GoTo EF
    I'm curious to see what romperstomper's suggestion yields. Could you elaborate on how I would iterate each cell and test each value against ID please?

    Much appreciation in advance.

  19. #19
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,998

    Re: UDF to capture change in cell values

    It would be:
    If IsError(r.value)

  20. #20
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    Apologies romperstomper I meant to direct this comment in my previous code to you, it didn't come across that way...

    I'm curious to see what romperstomper's suggestion yields. Could you elaborate on how I would iterate each cell and test each value against ID please?

  21. #21
    Forum Expert
    Join Date
    03-31-2009
    Location
    Barstow, Ca
    MS-Off Ver
    Excel 2002 & 2007
    Posts
    2,164

    Re: UDF to capture change in cell values

    quick answer. This will get you started.

    function Trigger(ByVal rEntireRange as Range) as date
        For Each rCell in rEntireRange
            If (not isempty(rcell))  and (not iserror(rcell)) and (rcell.id <> rcell.value) Then
                msgbox rcell.address & " is changed"
                rCell.id = rcell.value
            End If
        Next rCell
        Trigger = Now
    End Function
    You seem to be saying that you don't want the value N/A to remain in the cell. Do you want to replace the N/A with the old value? If so, then figure out what to check in order know to replace it with .id.
    Last edited by foxguy; 11-24-2011 at 09:23 PM.

  22. #22
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    Hi foxguy, I don't see how this function is storing/comparing values in each cell. The rCell.ID (ie. $A$1) is always going to be different to the rCell.Value (ie. 256) so this would prompt me with a msgbox for every cell in the range when I make a single change. Can you please shed some light on this alternative because I'd really like to understand how this method would work.

  23. #23
    Registered User
    Join Date
    03-07-2011
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    55

    Re: UDF to capture change in cell values

    RomperStomper, I have been using foxguys suggestion for the last month and reaching 1000+ lines using this UDF and it's doing the job but I would really like to explore your suggestion of using ID property of each cell to compare values. I'm thinking in order to make this solution scalable to 2000+ lines I need to find a more efficient method. Can you please elaborate on how I can acheive this?

    Thanks

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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