Esat Genç
Esat Genç

Reputation: 113

Can't write string in a cell from UDF

Sub Makro()

    Dim a As String
    Dim b As String

    Cells(1, 1).Value = myfunction(X, X)

    If Range("A1") = "XX" Then

        MsgBox "True"
    Else

        MsgBox "False"

    End If

End Sub

Function myfunction(a, b) As String

    myfunction = a + b

End Function

"A1" cell value equals 0. It must be XX.

Upvotes: 1

Views: 102

Answers (3)

user4039065
user4039065

Reputation:

Use the ampersand (e.g. &) for explicit string concatenation. While the plus sign (e.g. +) can be used due to VBA's overhead and it's attempts at cross platform compatibility, the primary operator for the plus sign is mathematical addition, not string concatenation and it will chose to add two digits if it can.

Function myfunction(a, b) As String
    myfunction = a & b
End Function

With the + as the string concatenation operator, if you passed 6 and 7 into the original function, you would receive 13, not 67. With the & you return 67.

Upvotes: 0

AndyW
AndyW

Reputation: 440

You are sending X to myfunction it should be "X". VBA is interpreting the X as a variable not a string

Cells(1, 1).Value = myfunction("X", "X")

Upvotes: 1

Rafael
Rafael

Reputation: 146

the X must be between " ", like:

Cells(1, 1).Value = myfunction("X", "X")

Upvotes: 1

Related Questions