[英]How to return custom type from VBA function
我想從VBA函數返回自定義類型。 當我運行以下代碼時,我得到一個錯誤“錯誤在第16行-類型不匹配”。 我不太了解發生了什么問題。
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
嘗試這個
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
但是GetName = temp
應該正常工作
這就是我的工作方式,刪除了函數的Set()
:
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
引入myFullName
是為了區分FullName
類型和具有相同名稱的變量。 在C#中,我會使用fullName
和FullName
,但是在VBA中,不支持這種“豪華”。
請嘗試一下
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.