Reputation: 59
I want to return a custom defined type from a VBA function. When I run the following code I get a error "Error on line:16 - type mismatch". I don't really understand what is going wrong.
Type FullName
FirstName As String
LastName As String
End Type
Sub Main
Dim fullName As FullName
fullName = GetName()
MsgBox fullName.FirstName &" "& fullName.LastName
End Sub
Function GetName() As FullName
Dim temp As FullName
temp.FirstName = "John"
temp.LastName = "Doe"
Set GetName = temp
End Function
Upvotes: 1
Views: 1348
Reputation: 21
PLease Give try on this
Public Type FullName
FirstName As String
LastName As String
End Type
Function GetName() As FullName
Dim temp As FullName
temp.FirstName = "John"
temp.LastName = "Doe"
GetName = temp
End Function
Upvotes: 1
Reputation: 43575
This is how I made it work, removing the Set()
at the function:
Option Explicit
Type FullName
FirstName As String
LastName As String
End Type
Sub Main()
Dim myFullName As FullName
myFullName = GetName()
Debug.Print myFullName.FirstName & " " & myFullName.LastName
End Sub
Function GetName() As FullName
Dim temp As FullName
temp.FirstName = "John"
temp.LastName = "Doe"
GetName = temp
End Function
The myFullName
is introduced, in order to differentiate between the type FullName
and the variable with the same name. In C#, I would have used fullName
and FullName
, but in VBA this "luxury" is not supported.
Upvotes: 1
Reputation: 12167
Try this
Function GetName() As fullName
Dim temp As fullName
temp.FirstName = "John"
temp.LastName = "Doe"
With temp
GetName.FirstName = .FirstName
GetName.LastName = .LastName
End With
End Function
But GetName = temp
should be working as well
Upvotes: 3