Excel 如何从VBA函数返回自定义类型
我想从VBA函数返回自定义定义的类型。当我运行下面的代码时,我得到一个错误“error on line:16-类型不匹配”。我真的不明白出了什么问题Excel 如何从VBA函数返回自定义类型,excel,vba,Excel,Vba,我想从VBA函数返回自定义定义的类型。当我运行下面的代码时,我得到一个错误“error on line:16-类型不匹配”。我真的不明白出了什么问题 键入全名 名字作为字符串 LastName作为字符串 端型 副总管 将fullName设置为fullName fullName=GetName() MsgBox fullName.FirstName&&fullName.LastName 端接头 函数GetName()作为FullName 作为全名的Dim temp temp.FirstName=“
键入全名
名字作为字符串
LastName作为字符串
端型
副总管
将fullName设置为fullName
fullName=GetName()
MsgBox fullName.FirstName&&fullName.LastName
端接头
函数GetName()作为FullName
作为全名的Dim temp
temp.FirstName=“约翰”
temp.LastName=“Doe”
设置GetName=temp
端函数
试试这个
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
应该也能正常工作试试这个
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中,不支持这种“豪华”功能。我就是这样做的,在函数处删除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
请试穿一下这个
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
你能试试[GetName=temp]而不是[Set GetName=temp]吗?我试过了,但结果还是一样。我打开了一个新的Excel,创建了一个新模块,粘贴了代码,并检查了失败的原因。然后退出“设置”。它运行正常。好的,我在伦巴脚本引擎中运行它。所以,也许这就是问题所在。你能试试[GetName=temp]而不是[Set GetName=temp]吗?我试过了,但结果是一样的。我打开了一个新的Excel,创建了一个新模块,粘贴了代码,并检查了失败的原因。然后退出“设置”。它运行正常。好的,我在伦巴脚本引擎中运行它。所以,也许这就是问题所在,现在我看到“第20行出现错误:GetName\uuuuu.FirstName=.FirstName”。我正在伦巴大型机模拟器的伦巴脚本引擎中运行这段代码。但这只是使用VBA和一些额外的命令,我没有伦巴脚本引擎,并假设您在excel及其VBA引擎中使用此代码,如标记所示。这是一个不同的故事,现在我得到了“第20行的错误:GetName\uuuuu.FirstName=.FirstName”。我正在伦巴大型机模拟器的伦巴脚本引擎中运行这段代码。但这只是使用VBA和一些额外的命令,我没有伦巴脚本引擎,并假设您在excel及其VBA引擎中使用此代码,如标记所示。这是一个不同的故事。