0

For first of all, this is my first time when try to use vba in excel. I know nothing about it.

I try to create a new function, into excel, to set a value in a specific cell.

I have this module:

Public Function SETVALUE(cell As Range, newValue As Integer) As String

    cell.value = newValue

    SETVALUE = "-"

End Function

This is my module:

If I type: =SETVALUE(A2, 1) in cell A1, it not work.

In cell A1 appear #Value! and in cell A2 appear nothing.

3
  • A function called by the worksheet cannot modify the value of another cell. Commented Jul 26, 2019 at 19:36
  • I would say it's probably not a good idea to do it but it's possible, see here Commented Jul 26, 2019 at 19:39
  • @ScottCraner so, I can't achieve that? Commented Jul 26, 2019 at 19:39

2 Answers 2

1

Try this

Option Explicit

Public Function SETVALUE(cell As Range, newValue As Integer) As String

    Evaluate "mySetValue( " & Chr(34) & cell.Address & Chr(34) & "," & Chr(34) & newValue & Chr(34) & ")"
    SETVALUE = "-"

End Function


Sub mySetValue(cell As String, newValue As Integer)
    Dim rg As Range
    Set rg = Range(cell)
    rg.Value2 = newValue
End Sub

Update: Image how to use it

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

The formula you typed contains an error: =SETVALUE(A2, 1)
What do you mean?
I type that formula into A1 and hit enter and get that error: The formula you typed contains an error. Also, in module, after type Range it change into range
My mistake I put , at A2, 1. It need to be ;. Thanks!
0

See here this article that 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: Insert, delete, or format cells on the spreadsheet. Change another cell's value.

The solution is to pass by a sub-routine Like this

Public Function SETVALUE(cell As Range, newValue As Integer) As String

Dim updateCell As String

SETVALUE = "-"

updateCell = "updateRange(" & cell.Address(False, False) & "," & newValue & ")"
Evaluate (updateCell)

End Function

Sub updateRange(vCell As Range, vNewValue As Integer)

vCell = vNewValue

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.