繁体   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