Page 3 of 3 FirstFirst 123
Results 21 to 24 of 24

Thread: UDF that can change values in cells other than the cell in which the UDF is used

  1. #21
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    10,456
    Rep Power
    10
    Question from the web[ ( https://www.excelforum.com/excel-pro...udf-error.html )


    The formula initially discussed in the first post of that Thread, at excelforum.com is possibly based on this one from the web/excelfox
    ____________=LOOKUP(1.1,1/(C:C<>""),C:C)
    https://www.excelfox.com/forum/showt...ll=1#post27585 https://www.exceldemy.com/excel-find...lue-in-column/
    https://www.excelfox.com/forum/showt...-in-a-column*)

    ( Here is the approximate equivalent version used in that excelforum Thread
    ____________=LOOKUP(2,1/(C[1]<>""),C[1])
    We will discuss that equivalent more later, but just one passing important fact to hear for the first time: The C in those formulas are not the same:
    In the first formula it is referring to the actual column C, the third column along to the right in an Excel spreadsheet. ( It was unfortunate I chose to use C in developing that formula, it was a bit silly really as it could confuse. Any column other than C or R would have been better )
    In the second formula the C itself is referring to columns in general, and usually a number associated with it tells us which column. (In that particular formula, it is the next column to the right of where the formula is written – 1 column to the right as it were)
    )


    The typical wrong answers, (as for example given initially in that excelforum thread)
    A UDF cannot add a formula to a cell.
    A UDF is a function that returns a value in the cell where it is called . …. A UDF cannot change the contents of any cell.


    I finally answered here in four posts, this one, #21, and then the following 3, #22, #23, #24.
    I am covering what I see as the three mains issues.
    This first post Post #21 https://www.excelfox.com/forum/showt...ll=1#post27596 is a bit of background and rambling from me
    , the meat of my answer is in the following three posts,
    Post #22 https://www.excelfox.com/forum/showt...ll=1#post27597
    Post # 23 https://www.excelfox.com/forum/showt...ll=1#post27597
    Post # 24 https://www.excelfox.com/forum/showt...ll=1#post27599





    The Full Question
    Code:
    I have a formula, that works, to find the last cell in a column: =Lookup(2,1/(rngInput<>""),rngInput)
    I used the macro recorder to produce the following which also works: 
    Code:
    Sub Macro1()
        ActiveCell.FormulaR1C1 = "=LOOKUP(2,1/(C[1]<>""""),C[1])"    
    End Sub
    I have tried to adapt the macro to create a UDF:
    Code:
    Function LastValue(rngInput As Range)
    Dim WorkRange As Range
     Set WorkRange = rngInput.Columns(1).EntireColumn
     ActiveCell.FormulaR1C1 = "=LOOKUP(2,1/(WorkRange<>""""),WorkRange)"
    End Function
    The function fails with the error #VALUE






    So, I can see approximately three main issues to consider.
    _ (i) Possibly an issue of using a UDF to add a formula to a cell. Often regarded as impossible, as per the wtong answers referenced. But I figured it out a few years back, in 2018, ( in this main Thread, ( the one I am posting in now ) . ) So we can do that, and ignore the first few replies in the excelforum.com Thread, treating them as misleading rubbish
    _ (ii) An issue of the correct formula syntax, not necessarily the problem that the original question poster , Marnhullman, thought h had. But there are some syntax problems.
    _ (iii) An issue that the helpers at excelforum.com went off in their usual frenzy of trying to get as many quick posts in as possible and may have missed the point and therefore complicated the issue making it difficult for the original question poster , Marnhullman, to easily follow. (Added to that we have the usual annoying over zealous nauseating Moderator contributions from Moderator AliGW, who/which seems to get on everyone’s backs apart from a few almost as mad senior members, Moderators, Admis, etc. who in the meantime have become her obedient minions or her good little school children..)


    I will address the 3 issues in the reverse order

    _(iii) What is wanted.
    This is all a bit of an aside, and some ramblings from me

    I cannot be sure either of exactly what is wanted, but we don’t have the distraction of the over zealous Hacks here at excelfox, so we may get slightly closer, even if it takes longer. Quality and imparting knowledge, furthering the subject, not racing to get as many short answers in for AI to learn from so as to help destroy Human thinking.

    A bit of background:
    Now, the term UDF, (User Defined Function), is not a term whose definition is fixed in stone. It usually means something along the lines of like this example: ….

    Simple example of what UDF usually is about
    We will follow the steps of somebody making himself a UDF….
    _"....There is not a built in function/ formula in Excel to do what I want. So I will make one., like this example:
    Say, I want to say Hello in a specified language…..

    So I put this coding in a normal code module

    Code:
    Public Function Hi(ByVal Langwidge As String) As String
        If Langwidge = "German" Then
         Let Hi = "Guten Tag"
        ElseIf Langwidge = "English" Then
         Let Hi = "Hello"
        Else
         Let Hi = "Huh?"
        End If
    End Function
    Now, if I go into an Excel Spreadsheet and type in any cell this
    =Hi("English")
    , then, after hitting Enter I will see in that spreadsheet cell the following
    Hello
    , and in the formula bar I will see what I typed
    =Hi("English")

    https://imgur.com/wO6lh6E ____ https://i.postimg.cc/859FdcdN/Hi-English.jpg





    So that was just an example of what a UDF usually is regarded as, or what a UDF is talking about.

    But the UDF definition is not set in stone. You might just call all that a custom function, or a user written function.
    Occasionally the term UDF might be used a bit loosely for any coding a user might write.
    Instead of coding we might say a macro or a procedure

    That was all a bit of an aside


    .

    It is not completely clear if Marnhullman knows exactly what best he wants, which would be normal, as Excel and VBA is so vast and diverse that there are usually a lot of different ways to do anything.

    But I think I have approximately covered issue _( iii )





    Now, My go at answering the question from here would be:
    I would tend to keep initially to
    _ variations of the formula, that Marnhullman said works, that being the formula to find the last cell in a column,
    , and
    _ the macro recording that Marnhullman said works
    That would approximately cover issue _(ii)

    , then I would take it from there, considering approximately issue _(iii) as last. issue _(iii) is what this main tutorial Thread is about, but it us a bit advanced and we won't lt ourselves get tunnel versioned for the sake of cold neatness and order.





    I will move on to the second issue _(ii) in the next 2 posts. That is mainly a discussion of the correct syntax for putting a formula in a cell. We need to get that correct bfore we do anything more advanced.
    Last edited by DocAElstein; 12-01-2025 at 10:04 PM.

  2. #22
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    10,456
    Rep Power
    10
    _(ii) The formula(s) and syntaxes thereof

    _(ii) a) Discussing the formula from the macro recorder and the attempt at adapting it.


    At first glance, I am not too happy with the look of this attempt from Marnhullman to adapt what he got from the macro recorder.

    Code:
    Dim WorkRange As Range
     Set WorkRange = rngInput.Columns(1).EntireColumn
     ActiveCell.FormulaR1C1 = "=LOOKUP(2,1/(WorkRange<>""""),WorkRange)"
    Although there may be some way to consider that correct using Named Ranges, my initial feeling is that the syntax is a bit out of whack there
    The main thing that concerns me is that the right hand side should look something like I might physically write in the cell, so Excel spreadsheet syntax, but it looks at first glance to me that we have got a VBA variable in that formula, WorkRange.

    Marnhullman was not happy with that either, or rather it did not work.

    Let’s go back to his macro recording (that did work), and discuss that a bit. ( ActiveCell.FormulaR1C1 = "=LOOKUP(2,1/(C[1]<>""""),C[1])" )
    Now, the macro recorder is a bit awkward when getting formulas from it as it inconveniently and annoyingly works in a so called …..
    _ "R1C1" format, which is a row number and column number format ( that is what the R (row) and C (column) is about )
    , that format is a different convention to the more typically used
    _ column letter and row number format that most of us are more familiar with. This more common column letter and row number format is what we see by default settings in a spreadsheet. For example, along the top we see letters A B C D E F …. etc. for the columns. Most people ever using Excel will be familiar with that, but not so many people will know what the "R1C1" row number and column number format is all about


    At the start of the last post I noted in passing a fact that is a bit of an unfortunate coincidence. It is important, so I will mention all that again
    This is an example formula that me ( and I expect a few others ) came up with a few years ago, which in the meantime is appearing in a few Blog sites and forum posts. It gets the last used cell in column C
    It was unfortunate that of all columns I chose column C. (Choosing column R would also have been a bad choice).
    ____________=LOOKUP(1.1,1/(C:C<>""),C:C)
    https://www.excelfox.com/forum/showt...ll=1#post27585 https://www.exceldemy.com/excel-find...lue-in-column/
    https://www.excelfox.com/forum/showt...-in-a-column*)

    Here is the approximate equivalent version used in that excelforum Thread
    ____________=LOOKUP(2,1/(C[1]<>""),C[1])
    That is what Marnhullman got from the macro recorder, and it works for him
    It is very important to note, that in that second formula, the C is not column C. It is referring to columns in general. ( CColumns ) That is because the macro recorder is using the "R1C1" format which is a row number and column number format
    In this particular example, it has a [1] after the C. This means it will be the column to the right ( 1 to the right ) of wherever I write the formula in

    ( A minor point: 1.1 or 2 or 9999 as the look up value will do. It just has to be a number greater than 1 )

    If I try to reproduce the result from a macro recording that Marnhullma got, I might get some more clues to what we want, as well as helping me get the correct syntax, since I also frequently get all these things mixed up.
    So, here I go:
    If I want to try and repeat something similar to what Marnhullma did, that is to say get a coding from a macro recording similar, then for that I could do this, ….
    _ First, Click any cell, say W6
    _ second, now type in the basic formula, and when I select the column to be used as my work range, I select the next column, X in this example
    https://i.postimg.cc/WpGmN519/Macro-...-1-C-1-C-1.jpg


    I then get this formula from the macro recorder
    ActiveCell.FormulaR1C1 = "=LOOKUP(1.1,1/(C[1]<>""""),C[1])"

    If I re write that formula equivalent, ( for the case where that last formula was written in column W ), using the more typically used column number and row number format convention, then it will look like,
    ActiveCell.Formula = "=LOOKUP(1.1,1/(X:X<>""""),X:X)" – that is in effect what I wrote into cell W6

    In fact, we find that VBA automatically directly recognises are formula format convention, and either of these put the same formula into a cell
    ActiveCell = "=LOOKUP(1.1,1/(C[1]<>""""),C[1])" ' assuming written in column W, and we want column X for the work range
    ActiveCell = "=LOOKUP(1.1,1/(X:X<>""""),X:X)"

    In the cell, by default settings we are in column letter and row number format, and will always see
    =LOOKUP(1.1,1/(X:X<>""),X:X)

    OK, so we are in tune on the macro recording produced formula and have also discussed how the formula would be written in the more typically used column letter an row number format.

    We won’t move on in this post to the final solution of a UDF to add a formula to a cell. Rather we will consolidate our knowledge of the correct syntax when using coding to put a formula into a cell.




    _(ii) b) The correct syntax in coding to put a formula into a cell

    We discussed that the macro recorder gives us the formula in the less typically used row number and column number format. I don’t think I have ever found that very useful, Other than perhaps a quick way to get to see how a formula written in the conventional column letter and row number format then looks in the less typical row number and column number format. That is basically what Marnhullman did. He wrote the formula he had in the column letter and row number format in a cell, and the information the macro recorded coding gave us was the equivalent formula in the row number and column number format. I don’t think this helps us much**. We are not particularly interested in how the formula would look in the row number and column number format. That does nothing significant for us, as far as I can see. (It helps a bit with tricky quote format maybe**, that's all)

    So in this case the macro recorder is of not much use to us. It is almost a Red Herring, because If I already have a formula in the column letter and row number format in a cell, for a simple example, consider a simple cell addition formula that I might write in a cell to add the values in two cells:
    = A1 + A2
    , then the coding for that is simply something like
    ActiveCell = "= A1 + A2"
    Simple. I already have what I need.
    I don’t need to do a macro recording, as it will give me this, for example if I write the formula in cell O28
    ActiveCell.FormulaR1C1 = "=R[-27]C[-14]+R[-26]C[-14]"
    That will work, for cell O28, but then the following will work in any cell
    ActiveCell = "= A1 + A2"




    The only awkward thing sometimes is when we want quotes in a formula in a cell. The problem is that in VBA coding the quote pair is used to tell VBA that we are giving literal text rather than coding within that quote pair, like

    "This is literal text, not coding, when written in VBA"

    This without being enclosed in a quote pair had better be correct coding syntax or else you will get an error in VBA


    So there is a bit of a dilemma when our literal string itself has quotes in it, as VBA will get a bit confused. Now, nobody has really figured this one out exactly, but we find that for example that if, (forgetting formulas for now), I wanted to put in the active cell the text
    a"b
    , then this would do it for me with VBA coding
    Let ActiveCell = "a""b"
    Nobody is quite sure what is going on there, but you might consider VBA as seeing this

    ____"a""b"

    In what ever way VBA looks at that it is happy to see either the red single quote within the syntaxly required enclosing blue quotes, or a blue single quote enclosed within the red quotes.
    At the same time, VBA is not erroring since it is seeing two lots of syntaxly correct quote pairs. (You will never get away in VBA coding with 1 or any odd number of quotes in a code line, since after a quote, it takes that as a start quote and wants to see the second terminating quote. If it does not find a terminating quote, then it will error)

    But the middle 2 quotes, be it the red or blue one, have somehow got themselves intimately entwined and so VBA sees those 2 in the same place. It is like the stop of one is in the same place as the start of the other.
    So in the final text we get just get the one quote.
    Think of that as writing a character twice in the same place – in the final text you only see one character.
    https://i.postimg.cc/0Q6bHcYg/Active-Cell-a-Quoteb.jpg



    That last bit was a bit of how I see it in my brain. So don't worry if you don't follow. The important result is that within ( within meaning inside the main two quotes "______" ) a literal text string in VBA, if I want to finally have a single quote in what I put/ see finally in a cell, then I type two quotes together in the VBA string

    We want a double quote in our formulas in the cell, so in VBA that would be 4 quotes based on the results/ conclusions we just discussed about how to put a single quote in a cell.
    Furthermore those quotes must be all together, - to explain that:
    Each pair of quote pair in VBA, within a literal text section, which produces a single quote in a cell, must be together, like any of these examples
    Code:
         VBA                 Excel – what I finally see and want
    "X   ""      Y"            X    "      Y
    "    "" ""    "                 " "
    "  "" xy "" "                  " xy "
    "    "" ""    "                  " "
    "    """"     "                  "" 
    "X   """"    Y"             X    ""    Y
    Some variation of the last 2 in green is what we want to finally have in the cell formula, ""
    So it follows that in VBA we write """"


    ( ** I suppose getting that correct quote syntax is maybe one useful thing the macro recorder did do for us, as that will be the same in the final coding whether we write the formula in the row number and column number format or the column letter and row number format. )



    OK, so we now know all about getting the quotes correct and we know we can choose to write the formula in either the row number and column number format or the column letter and row number format.


    So what is wrong with this, in terms of basic coding

    Set WorkRange = rngInput.Columns(1).EntireColumn
    ActiveCell.FormulaR1C1 = "=LOOKUP(2,1/(WorkRange<>""""),WorkRange)"


    There is nothing wrong with the first code line. ( But note, that if only one cell is in rngInput, then we don't need the Columns(1). )

    The problem is we need to get that string in the form that you would write it in a cell. That might work perhaps if WorkRange was a defined named range in the spreadsheet. But I will take a guess that it isn't. It is a VBA variable as given thus
    Dim WorkRange As Range

    Now, you can't go around writing a VBA range object variable in a spreadsheet cell. That is nonsense: That is a bit like trying to paste your entire car object onto a piece of paper when you really wanted to write its name or paste a picture of it on the piece of paper.

    We need the string text that is used in the cell, to represent that range object, in other words, we need the text as we would write it in manually
    For examples,
    _ the first cell in a spreadsheet can be written in the column letter and row number format, in a cell, as either A1 or $A$1
    , and
    _ an entire column, such as the 4th column of a spreadsheet can be written in the column letter and row number format as either D:D or $D:$D

    In VBA, we can get that string format from the .Address property, like this
    WorkRange.Address
    ( The default format returned is the column letter and row number format )
    https://i.postimg.cc/BnSWSTTN/Range-A1-Address.jpg



    _...... continued in next post….
    Last edited by DocAElstein; 10-22-2025 at 12:41 PM.

  3. #23
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    10,456
    Rep Power
    10

    Put formula in a cell with coding

    We are almost there.
    We need to make some construction using that WorkRange.Address within VBA that allows it to be used within the main formula string: We cannot just insert WorkRange.Address any more as we cannot just insert WorkRange, as it will take WorkRange.Address as just that actual text, as if we had given excel some text, like
    Let ActiveCell = "WorkRange.Address" ___
    , but we don't want that, we want the short text notation used in an Excel spreadsheet for a range, (that of the cell in the Excel spreadsheet column letter and row number format), that is returned from WorkRange.Address when it is used in VBA coding.

    The VBA coding syntax for doing that sort of thing is to insert it into the main formula string at the appropriate position in a special way like this
    _______________ " & WorkRange.Address & "
    What that does, is do the VBA business on WorkRange.Address and then stick the result into the literal text
    , pseudo like, if , for example, WorkRange was the second cell in a spreadsheet, ( Set WorkRange = Range("B1") ) then:
    " & WorkRange.Address & " will be turned by VBA into $B$1 , and that $B$1 will be inserted into the text.

    We are using it in a formula, but the idea is easier to see in a simple text, thus
    Code:
    Sub TextIn()
    Dim Rng As Range
     Set Rng = Range("A1")
     Let Range("D10") = "The first cell has an address of " & Rng.Address & ", honest"
    End Sub
    Rub that macro and then In the cell, D10 you will see
    The first cell has an address of $A$1, honest







    In this post we will now do some examples of how to put the basic formula into a cell. Some will be relevant to this Thread, some won't necessarily, - at the end of the day we are Human here and are not so keen to encourage the robots to take over with their well ordered cold logic!







    From now on I will use this simple test range, which is in both worksheets in the uploaded file. ( the letter f in cell E5 is the last filled cell in column E)
    https://i.postimg.cc/Kz4bFvvc/Simple-test-range.jpg


    _____ Workbook: SimpleCodingPutFormulasInCell.xls ( Using Excel 2007 32 bit )
    Row\Col E
    1
    2 a
    3 b
    4
    5 f
    6
    Worksheet: Sheet1

    Often, or at least initially, I will tend to put the formula somewhere to the left of the range, for no particular reason other than a guess that it could bee convenient there. Of course, if I am passing a work range, then that will determine where things are relatively speaking.

    Simplest Codings Put formula in
    I assume here that I want my formula in column D, and I have selected the cell in column D that I want the formula in.
    Here are three coding offerings
    Code:
    Sub PutFormulaIn_1()
     Let ActiveCell = "=LOOKUP(3,1/(" & ActiveCell.Offset(0, 1).EntireColumn.Address & "<>"""")," & ActiveCell.Offset(0, 1).EntireColumn.Address & ")"
    End Sub
    
    Sub PutFormulaIn_2a()
    Call PutFormulaIn_2b(ActiveCell.Offset(0, 1).EntireColumn)
    End Sub
    Sub PutFormulaIn_2b(ByVal WorkRange As Range)
     Let ActiveCell = "=LOOKUP(3,1/(" & WorkRange.Address & "<>"""")," & WorkRange.Address & ")"
    End Sub
    
    Sub PutFormulaIn_3a()
    Call PutFormulaIn_3b(ActiveCell.Offset(0, 1).EntireColumn)
    End Sub
    Function PutFormulaIn_3b(ByVal WorkRange As Range)
     Let ActiveCell = "=LOOKUP(3,1/(" & WorkRange.Address & "<>"""")," & WorkRange.Address & ")"
    End Function
    (The coding is also in the uploaded file, SimpleCodingPutFormulasInCell.xls )

    Run any of those codings, ( by running either of these:
    Sub PutFormulaIn_1()
    Sub PutFormulaIn_2a()
    Sub PutFormulaIn_3a()
    __
    ), and the result will be the same:
    In the selected cell, if it is in column D you will see f
    In the formula bar you will see =LOOKUP(3,1/($E:$E<>""),$E:$E)
    https://i.postimg.cc/BnZzPSR3/Result...ist-Coding.jpg


    Strictly speaking, none of those solutions is a UDF solution.
    The last function could be considered a UDF, if I called it from the spreadsheet by typing in any cell something like
    =PutFormulaIn_3b(E:E)

    If you try doing it just like that it will not work. That is where the typical answers come from, those answers of like ….
    …. A UDF cannot add a formula to a cell. …..

    In the next post I will show how that can be done. But before that I will throw in a solution of a different sort, just in case it might be worth considering….




    Simple alternative way to do it Event Coding
    This solution does not really fit in to this Thread. But we are not prejudice here at excel fox.

    Event Coding
    VBA can be thought very approximately as the coding that actually makes Excel or Microsoft Office work. Very graciously Microsoft let us tap into it, and so we can do an amazing number of things.
    (Using Microsoft Office without the VBA you already have, can be compared with having some all purpose vehicle parked outside your door, that can do just about everything that any vehicle can and much more like flying to Mars, submerging to the centre of the earth, digging out a trench to make a river to save a Forest for younger generations etc., etc., but you just use it once a week for the same short journey to go to the local shops )
    Microsoft do not let us do everything, understandably perhaps, or else we would make everything ourselves, or more likely make a mess.

    When things happen, for example, a cell value gets changed, various things happen, a chain of events occur, as it were. We can tap into those as well.
    We will do that in worksheet, Sheet2

    We go to the second worksheet, Sheet2, right click on the Sheet2 tab at the bottom, select View Code , that gets us the VB Editor we might be familiar with, but the biggest empty window showing is a special code module belonging to the worksheet. There is one such code module for each worksheet.
    https://i.postimg.cc/F15RRvcj/Mess-a...eet-Change.jpg


    Now mess around selecting things from the two drop downs you see at the top of the worksheet code module until you get the Worksheet_Change sub routine showing
    It is empty initially. It is part of the chain events that happen when something is changed in a worksheet. Microsoft do not want to show us all that goes on, but we can see this sub routine that is always done, or rather run, even though it does nothing as it is empty. But we can add coding to it, so that something else is done when there is a change in the worksheet.
    The Target variable is given to us and filled with the range object of what was changed. So that is handy, me thinks…..
    How about this:
    I will write a bit of coding to put in the empty routine, that checks what range got changed. If it was a single cell, and say, a small z was typed in, then I will put the formula in that cell, the formula that gives me the last value in the column to the right of that cell
    Here is the coding
    Code:
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Cells.Count = 1 And Target.Value2 = "z" Then
         Target.Select ' After I hit Enter I will be in the next cell down, so this puts me back in the cell I typed  z  in
         Call PutFormulaIn_3b(ActiveCell.Offset(0, 1).EntireColumn) '
        Else
        ' do nothing
        End If
    End Sub
    The coding is also in the uploaded file, SimpleCodingPutFormulasInCell.xls



    So just to recap, clarify what you do and what goes on in Sheet2:

    Select a cell (in Sheet2), to the left of the column you want to get the last value of, for example D4.
    Type a small z in it, and hit Enter
    The formula we want then gets put in that cell, ( the z is overwritten with the formula )



    For convenience I use the function PutFormulaIn_3b . I could just as well have put all the coding in , or indeed used any of the other routines .
    Code:
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Cells.Count = 1 And Target.Value2 = "z" Then
         Target.Select ' After I hit Enter I will be in the next cell down, so this puts me back in the cell I typed  z  in
    '     Call PutFormulaIn_3b(ActiveCell.Offset(0, 1).EntireColumn) '
    '     Call PutFormulaIn_1
    '     Call PutFormulaIn_2a
    '     Call PutFormulaIn_2b(ActiveCell.Offset(0, 1).EntireColumn)
         Call PutFormulaIn_3a
        Else
        ' do nothing
        End If
    End Sub
    


    Attached Files Attached Files
    Last edited by DocAElstein; 10-22-2025 at 12:52 PM.

  4. #24
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    10,456
    Rep Power
    10

    Doing the impossible, again

    A UDF to change the contents of any cell, in our case to put the formula in to get the last value in a column

    Here, we develop a UDF to put our formula in any cell of our choosing, ( well almost any cell, in any case a cell other than the one we use the UDF formula in – which is regarded as impossible)

    We will use the same test range in column E, as in the previous posts, in a third worksheet which I will name Marnhullman
    https://i.postimg.cc/KYs7c9cD/Ws-Marnhullman.jpg




    This is an example coding, and it is in th uploaded file. (You need all that coding)
    Code:
    Function PutFormulaIn_4a(rngInput As Range) As String
    Rem 1 ' The conventional use of a  UDF  to return a value in the cell that it is in, in a similar way to how a formula or in built function does
     Let PutFormulaIn_4a = "last in column " & Split(rngInput.Cells.Item(1).Address, "$")(1)   '      rngInput.Cells.Item(1).Address  will give us a simple string which will have a form like  $E$19   If isplit that using  $  as the delimeter,  I end up with three elements indicie  0  1  2  (0)is an empty string,  (1) is E  ,  (2)  will be the number
    
    Rem 2 ' Unconventional use of the general thing we might call a  UDF
     Worksheets("Marnhullman").Evaluate Name:="=PutFormulaIn_4b(" & rngInput.Address & "," & ActiveCell.Address & ")"  '    The   Evaluate("  ")  string, that is to say the   Name:="  "    bit in this case,   uses Excel spreadsheet syntax, not VBA syntax, and we can get that  spreadsheet  A1  type address syntax from the   .Address   stuff in VBA
    End Function
    Sub PutFormulaIn_4b(ByVal rngInput As Range, ActivCel As Range)
    Dim WorkRange As Range
     Set WorkRange = rngInput.Columns(1).EntireColumn
     Let ActivCel.Offset(1, 0).Value = "=LOOKUP(3,1/(" & WorkRange.Address & "<>"""")," & WorkRange.Address & ")"
    End Sub
    
    The first procedure, Function PutFormulaIn_4a, is what we might call the UDF.
    If, for example you were to type in cell D4
    =PutFormulaIn_4a(E3)
    https://i.postimg.cc/nL4vtHjx/Use-UDF-in-D4.jpg


    , then we will get the following formula written in a cell
    =LOOKUP(3;1/($E:$E<>"");$E:$E)
    https://i.postimg.cc/KYPnyZkS/Formula-put-in-D5.jpg



    This solution probably comes closes to answering the very initial post over at excelforum.com



    However, there are just a few deviations/ features to discuss , as well as a general explanation of what is going on.
    A couple of non perfections:
    _ This does not work to put the formula in the same cell as where you use the UDF. But it does work to put the formula in any other cell, (which is the thing regarded by most as impossible) . I have arranged that it puts the formula in the next cell down. That is what the
    .Offset(1, 0)
    , in the last code line is about – it is offset by 1 row down and 0 column offset. So you can change that as you wish to put the formula somewhere else, but avoid no offset, as that can cause a nasty crash. (I suspect that with no offset it may be trying to do two things simultaneously in a cell, which causes the nasty crash)
    _ Initially the formula always shows 0. I suspect that may be because for some reason it has not yet been done/ evaluated/calculated. But as soon as you do most other things in the worksheet, or save the file, or probably do various other things, then the worksheet seems to get refreshed, and the formula gets done. ( After that it will update as any formula would if you change any cell values that it is working on )


    General Explanation of what is going on
    If we consider the first part of Function PutFormulaIn_4a ( section Rem 1 ) , along with the example use I did above, then that is what a typical UDF is all about: What is going on there is that, some of the information you pass to it, (when you call it from a cell ), is used to put something in the cell you wrote in. In this example I have arranged that it puts some text in telling you which column you are trying to get the last value from.
    Rem 2 section and the other procedure, Sub PutFormulaIn_4b is part of the trick to get a formula out in a cell from when using a UDF. ( Whether or not Rem 2 section and the other procedure, Sub PutFormulaIn_4b is part of what we might refer to as the UDF named PutFormulaIn_4a is open to debate. That is perhaps convenient as the Experts claiming this cannot be done, can say the UDF is not changing the contents of any cell if they regard only Rem 1 section as a UDF )

    So Rem 2 section and the other procedure, Sub PutFormulaIn_4b gets the job done.
    Nobody is too sure what is going on here. But we know that in general the
    VBA Evaluate(" ")
    Or
    VBA Evaluate Name:=" "
    ( those are just 2 different syntaxes of the same thing )
    , is something that allows us to do things in VBA that we do in a spreadsheet cell. In other words, you can write in between the quotes pair what you can write in a cell. VBA then tries to give you the result as it would in the cell. So using it in the way I am here, seems to set off an independent second procedure. As it is somehow independent, it seems to work similarly to how any procedure I run normally from within VBA would work. So I do not have the restrictions that I have with the typical standard UDF.




    That is basically it.



    One small point is that we do have 2 VBA Evaluate things, a general one, and one for every worksheet. I have sometimes found that if I have a lot of these sorts of UDFs in different worksheets, then using one of them can inadvertently set the others off in the wrong worksheet. Restricting things to a worksheet, ( as I am doing in Rem 2 with Worksheets("Marnhullman"). ) seems to cure that problem. If you miss out the Worksheets("Marnhullman"). , then you default back the general Evaluate, and it may be OK, and you remove the restriction to a particular worksheet.
    An interesting observation is that in the second procedure, ActiveCell does not work as we might expect. ( That is why I had to pass over the address of the active cell in order to use it ). This observation supports some ideas about why this trick works: It is thought that Excel has lost its orientation a bit, when it runs the second procedure, which gives it the independence that helps make it work for our purpose. Now, surprisingly, ActiveCell is not a property of a worksheet, nor generally a property of Excel. It is a Windows property. So using Evaluate is doing spreadsheet things but somehow not directly linked to a worksheet. Hence we have interesting new possibilities using it. The VBA Evaluate function is often regarded by smart people as one of the most powerful functions.



    Alan
    Attached Files Attached Files
    Last edited by DocAElstein; 10-21-2025 at 02:33 PM.
    ….If you are my competitor, I will try all I can to beat you. But if I do, I will not belittle you. I will Salute you, because without you, I am nothing.
    If you are my enemy, we will try to kick the fucking shit out of you…..
    Winston Churchill, 1939
    Save your Forum..._
    KILL A MODERATOR!!

Similar Threads

  1. Question on UDF LookUpConcat
    By K2` in forum Excel Help
    Replies: 4
    Last Post: 05-07-2013, 10:25 PM
  2. Trouble implementing UDF's
    By ProspectiveCounselor in forum Excel Help
    Replies: 4
    Last Post: 05-06-2013, 08:07 PM
  3. Insert Picture in a Cell UDF
    By Admin in forum Download Center
    Replies: 10
    Last Post: 12-07-2012, 04:49 PM
  4. UDF to Create In-Cell Chart in Excel
    By Admin in forum Download Center
    Replies: 0
    Last Post: 08-13-2011, 09:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •