+ Reply to Thread
Results 1 to 15 of 15

Using VBA to populate cells with formulas containing user-defined functions

Hybrid View

  1. #1
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Using VBA to populate cells with formulas containing user-defined functions

    Hi,

    As per title, I'm trying to populate some formulas from VBA but having problems. This is the UDF and populating sub:

    Function GetDateIfValid(DateCell As Range)
    On Error GoTo CleanExit
    If IsDate(DateCell.Value) And DateCell.Value <= Date And DateCell.Offset(-1, 1) <> "D" Then
        GetDateIfValid = DateCell.Value
        Exit Function
    End If
    
    CleanExit:
    GetDateIfValid = ""
    Application.Calculate
    End Function
    
    Sub populateDatesFormulae()
    Dim TC As String
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    
    For Each cell In Range("A2:A60")
        TC = Cells(2, (cell.Row - 1) * 3).Address
        cell.Formula = "=GetDateIfValid(INDIRECT(""'Employee Tracking'!" & TC & """))"
    Next cell
    
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    End Sub
    When I run it I just get the hourglass until I hit escape. It puts the formula into the first cell correctly but it has a '#VALUE!' error and does not continue with the other cells. If I then hit 'calculate' the formula works fine.

    edit - I've now found that if I leave the calculation as automatic it will populate all the cells but still hangs afterwards.

    Been messing around for a while with this so any suggestions would be gratefully received.

    Thanks,

    Chinchin
    Last edited by Chinchin; 08-28-2011 at 01:56 PM.

  2. #2
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    (deleted because it was wrong)
    Last edited by Chinchin; 08-28-2011 at 11:08 AM.

  3. #3
    Forum Expert Bob Phillips's Avatar
    Join Date
    09-03-2005
    Location
    Wessex
    MS-Off Ver
    Office 2003, 2010, 2013, 2016, 365
    Posts
    3,284

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Function GetDateIfValid(DateCell As Range)
        On Error GoTo CleanExit
        If IsDate(DateCell.Value) And DateCell.Value <= Date And DateCell.Offset(-1, 1) <> "D" Then
            GetDateIfValid = DateCell.Value
            Exit Function
        End If
        
    CleanExit:
        GetDateIfValid = ""
    End Function
    
    Sub populateDatesFormulae()
    Dim TC As String
    Dim cell As Range
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        
        For Each cell In Range("A2:A60")
            TC = Cells(2, (cell.Row - 1) * 3).Address
            cell.Formula = "=GetDateIfValid(INDIRECT(""'Employee Tracking'!" & TC & """))"
        Next cell
        
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
    End Sub

  4. #4
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Thanks Bob, that's done it. I did put the application.calculate in for a reason earlier (I think it made the UDF refresh when I changed it), but it's not necessary now so this will do nicely.

    Chinchin

  5. #5
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Do you need to use INDIRECT in the formula?
    Option Explicit
    
    Function GetDateIfValid(DateCell As Range)
        If IsDate(DateCell.Value) And DateCell.Value <= Date And DateCell.Offset(-1, 1) <> "D" Then
            GetDateIfValid = DateCell.Value
        Else
            GetDateIfValid = ""
        End If
    End Function
    
    Sub PopulateDatesFormulae()
        Dim TC As String
        Dim Cell As Range
        
        On Error GoTo ResetApplication
        
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
            .Calculation = xlCalculationManual
        End With
    
        For Each Cell In Range("A2:A60")
            TC = Cells(2, (Cell.Row - 1) * 3).Address
            Cell.Formula = "=GetDateIfValid('Employee Tracking'!" & TC & ")"
        Next Cell
        
    ResetApplication:
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = xlCalculationAutomatic
        End With
    End Sub
    If you need any more information, please feel free to ask.

    However,If this takes care of your needs, please select Thread Tools from menu above and set this topic to SOLVED. It helps everybody! ....

    Also
    اس کی مدد کرتا ہے اگر
    شکریہ کہنے کے لئے سٹار کلک کریں
    If you are satisfied by any members response to your problem please consider using the small Star icon bottom left of their post to show your appreciation.

  6. #6
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    I use INDIRECT when I want to stop formulas from changing when a user drags a referenced cell. Do you know of a better way to do that?

  7. #7
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: Using VBA to populate cells with formulas containing user-defined functions

    In this case the formula will not change when dragged it is inserted as an absolute reference by the code
    e.g.
    =GetDateIfValid('Employee Tracking'!$C$2)
    By using the $ "anchors" you can decide whether the formula changes or not as it is dragged.

    INDIRECT() is a volatile function and will recalculate every time your workbook calculates, this can be very memory intense, so it is best avoided if possible.

    Best you protect the sheet to avoid users dragging formula at will.

    Try the code I posted in Post #5

  8. #8
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Thanks Marcol but I was meaning if, in this example, the user moves cell C2. The $ signs don't stop the reference changing.

    I do use INDIRECT quite a lot to prevent this so that's a bit concerning if it uses too much memory - is there a different way to do it when the user must have access to the referenced cells? Also, how often is a workbook recalculating all the INDIRECTs?

    Thanks,

    Chinchin

  9. #9
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: Using VBA to populate cells with formulas containing user-defined functions

    It will recalculate the volatile functions every time the workbook changes and recalculates anything, regardless if the formula is on the active worksheet or not.
    See this link
    ... Volatile and Non-Volatile Functions

    By locking/unlocking cells then protecting the sheet, you can decide what cells the user has access to. You can allow the user to edit/enter data in a cell but not be able to drag it.
    See this link
    Lock or unlock specific areas of a protected worksheet

    Avoid using the volatile formulae where-ever possible, certainly never use them to "protect" formula.

  10. #10
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Thanks Marcol, I've removed all the INDIRECTs now and it does seem to run a bit quicker. however, I can't find any way to prevent dragging except for using application.celldraganddrop = false (which is undesirable because it will affect other open workbooks and can also be changed by the user so I'd have to keep setting it on selection change events).

    Is there another way that I'm missing? I couldn't see one in the sheet protection link.

    Thanks,

    Chinchin

  11. #11
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Can you post a sample workbook that explains/shows your problem?

  12. #12
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Please find attached.

    The 'formulas' table needs to always show the values form the corresponding position in the data entry table regardless of what the user does (for example, try dragging the '1' to another cell - the formulas using INDIRECT show what needs to happen).

    Preventing the user from dragging would be ok too, but the way the INDIRECT formulas work is preferable since dragging can speed up the data entry and users are used to it being available.

    Thanks,

    Chinchin
    Attached Files Attached Files
    Last edited by Chinchin; 08-29-2011 at 10:26 AM.

  13. #13
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Looks like Named Ranges and/or Sheet Protection might be your best options.

    1/. Create a Named Range for the Data Entry Table
    Name:= DataEntryForm
    Refers To :=
    =Sheet1!$B$3:$D$7
    2/. In G3
    =INDEX(DataEntryForm,ROW($A1),COLUMN(A$1))
    Drag Across to I3 Then Down to Row 7

    3/. Protect the sheet but allow manual entry to the Data Table.
    Select B3:D7
    Format > Format Cells ...
    In the Protection Tab Uncheck Locked > Press Okay

    Format > Protection:=Protect Sheet
    You can enter a password and select the desired options, but for this exercise just Press Okay

    Try what you need to do with the Data Table.

    Now unprotect the sheet
    Format > Protection:=Unprotect Sheet

    Select B3:D7 and drag the whole table somewhere else on the sheet.
    The new formula should still display correctly, but the Indirect method will fail.

    This is just to illustrate what is possible to control, there are many more permutations that you can use.
    Attached Files Attached Files

  14. #14
    Registered User
    Join Date
    04-12-2011
    Location
    Leeds, England
    MS-Off Ver
    Excel 2007/2010
    Posts
    67

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Clever stuff. So basically I'm using protected cells to build up a reference to the user's cells. I'd not sure I'd ever have thought of doing it that way - thanks very much.

    Chinchin

  15. #15
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: Using VBA to populate cells with formulas containing user-defined functions

    Way to go buddy ...
    Happy to have helped.

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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