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
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
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.