Link to home
Start Free TrialLog in
Avatar of cadwal01
cadwal01

asked on

Excel User Defined Function to Change Locked Status of Range

I am trying to auto-(un)lock a range based on a value in another column.  As a simple example I have three cells and am trying to use a user defined function to solve instead of a long loop cycle.

D5: is the value that drives the change (1=unlock,else=lock)
E5: UDF (see code below)
G5: range to lock

On page UDF first
=LockIt(D5,"G5")

Open in new window


The module level function
Public Function LockIt(ByVal nlValue As Integer, ByVal rangeIN As String) As Boolean
On Error GoTo ErrHandler:

    Dim lLock As Boolean
    Dim lSuccess As Boolean
    
    If nlValue = 1 Then
        lLock = False
    Else
        lLock = True
    End If
    
     Sheet1.range(rangeIN).Locked = lLock

    Debug.Print Sheet1.range(rangeIN).Locked
    
    LockIt = lLock

ErrCleanup:
    LockIt = lSuccess
    Exit Function
ErrHandler:
    lSuccess = False
    MsgBox Err.Description, vbExclamation + vbOKOnly, "Error Encountered"
    Resume ErrCleanup
End Function

Open in new window


The code is running without error, but the range lock status is not happening.  

Thanks.
Avatar of Anthony Berenguel
Anthony Berenguel
Flag of United States of America image

"The code is running without error, but the range lock status is not happening. "

do you mean that part of the selection structure is not being hit when it you expect that it should?
ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
that's good to know, imnorie. I've been trying to troubleshoot this code to work but with no success. No doubt because UDFs are not meant to accomplish this sort of task.

cadwal01, maybe you need to do this with a user-triggered macro or with the worksheet_change event.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cadwal01
cadwal01

ASKER

Unfortunately, and I forgot to mention, I had to develop this in 2003 b/c of client environment.  Kind of figured this would be the answer.  Appreciate the insights.
It's not a version thing as far as I know, you've never been able to use VBA UDFs for this sort of thing.

Also, I'm afraid you can't really use the Change event - it's not triggered by value of a formula changing.

If you wanted to use the Change event I suppose you could monitor other cells, but that might not be practical if you don't know where the UDF will be used and what cell references might be used in it.