簡體   English   中英

如何從VBA函數返回自定義類型

[英]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#中,我會使用fullNameFullName ,但是在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM