Using a UDF in Excel to update the worksheet

后端 未结 3 1505
心在旅途
心在旅途 2020-11-22 02:01

Not really a question, but posting this for comments because I don\'t recall seeing this approach before. I was responding to a comment on a previous answer, and tried some

3条回答
  •  余生分开走
    2020-11-22 02:47

    The MSDN KB is incorrect.

    It says

    A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following:

    1. Insert, delete, or format cells on the spreadsheet.
    2. Change another cell's value.
    3. Move, rename, delete, or add sheets to a workbook.
    4. Change any of the environment options, such as calculation mode or screen views.
    5. Add names to a workbook.
    6. Set properties or execute most methods.

    In the below code you can see points 1, 2,4 and 5 can be easily achieved.

    Function SetIt(RefCell)
        RefCell.Parent.Evaluate "SetColor(" & RefCell.Address(False, False) & ")"
        RefCell.Parent.Evaluate "SetValue(" & RefCell.Address(False, False) & ")"
        RefCell.Parent.Evaluate "AddName(" & RefCell.Address(False, False) & ")"
    
        MsgBox Application.EnableEvents
        RefCell.Parent.Evaluate "ChangeEvents(" & RefCell.Address(False, False) & ")"
        MsgBox Application.EnableEvents
    
        SetIt = ""
    End Function
    
    '~~> Format cells on the spreadsheet.
    Sub SetColor(RefCell As Range)
        RefCell.Interior.ColorIndex = 3 '<~~ Change color to red
    End Sub
    
    '~~> Change another cell's value.
    Sub SetValue(RefCell As Range)
       RefCell.Offset(, 1).Value = "Sid"
    End Sub
    
    '~~> Add names to a workbook.
    Sub AddName(RefCell As Range)
       RefCell.Name = "Sid"
    End Sub
    
    '~~> Change events
    Sub ChangeEvents(RefCell As Range)
        Application.EnableEvents = False
    End Sub
    

提交回复
热议问题