Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

excel - VBA: How to change the value of another cell via a function?

I'm an Excel VBA newbie.

How to change the value of the specified cell via a user-defined function? What's wrong with this code:

Function Test(ByVal ACell As Range) As String
  ACell.Value = "This text is set by a function"
  Test := "Result"
End Function

My wish is ... when I type =Test(E6) in cell E1, Excel will display the specified text in E6.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

YES, of course, it is possible.

enter image description here

Put this code in Module1 of VBA editor:

Function UDF_RectangleArea(A As Integer, B As Integer)
    Evaluate "FireYourMacro(" & Application.Caller.Offset(0, 1).Address(False, False) & "," & A & "," & B & ")"
    UDF_RectangleArea = "Hello world"
End Function

Private Sub FireYourMacro(ResultCell As Range, A As Integer, B As Integer)
    ResultCell = A * B
End Sub

The result of this example UDF is returned in another, adjacent cell. The user defined function UDF_RectangleArea calculates the rectangle area based on its two parameters A and B and returns result in a cell to the right. You can easily modify this example function.

The limitation Microsoft imposed on function is bypassed by the use of VBA Evaluate function. Evaluate simply fires VBA macro from within UDF. The reference to the cell is passed by Application.Caller. Have fun!

UDF limitation documentation: https://support.microsoft.com/en-us/help/170787/description-of-limitations-of-custom-functions-in-excel


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...