所以我想知道,如何从VBA中的函数,子或类型返回多个值? 我有这个主要的子应该从几个函数收集数据,但一个函数只能返回它看起来的一个值。那么如何将多个返回给子?
答案 0 :(得分:49)
您可能希望重新考虑应用程序的结构,如果您真的想要一种方法来返回多个值。
要么分开,要么不同的方法返回不同的值,或者找出逻辑分组并构建一个对象来保存可以返回的数据。
' this is the VB6/VBA equivalent of a struct
' data, no methods
Private Type settings
root As String
path As String
name_first As String
name_last As String
overwrite_prompt As Boolean
End Type
Public Sub Main()
Dim mySettings As settings
mySettings = getSettings()
End Sub
' if you want this to be public, you're better off with a class instead of a User-Defined-Type (UDT)
Private Function getSettings() As settings
Dim sets As settings
With sets ' retrieve values here
.root = "foo"
.path = "bar"
.name_first = "Don"
.name_last = "Knuth"
.overwrite_prompt = False
End With
' return a single struct, vb6/vba-style
getSettings = sets
End Function
答案 1 :(得分:20)
您可以尝试返回VBA集合。
只要您处理配对值,例如“Version = 1.31”,您就可以将标识符存储为键(“Version”),将实际值(1.31)存储为项目本身。
Dim c As New Collection
Dim item as Variant
Dim key as String
key = "Version"
item = 1.31
c.Add item, key
'Then return c
之后访问这些值很简单:
c.Item("Version") 'Returns 1.31
or
c("Version") '.Item is the default member
有意义吗?
答案 2 :(得分:12)
想法:
答案 3 :(得分:8)
您还可以使用变量数组作为返回结果来返回任意值序列:
Function f(i As Integer, s As String) As Variant()
f = Array(i + 1, "ate my " + s, Array(1#, 2#, 3#))
End Function
Sub test()
result = f(2, "hat")
i1 = result(0)
s1 = result(1)
a1 = result(2)
End Sub
丑陋且容易出错,因为你的调用者需要知道返回什么才能使用结果,但偶尔会有用。
答案 4 :(得分:4)
一个函数返回一个值,但它可以"输出"任意数量的价值观。示例代码:
Function Test (ByVal Input1 As Integer, ByVal Input2 As Integer, _
ByRef Output1 As Integer, ByRef Output2 As Integer) As Integer
Output1 = Input1 + Input2
Output2 = Input1 - Input2
Test = Output1 + Output2
End Function
Sub Test2()
Dim Ret As Integer, Input1 As Integer, Input2 As Integer, _
Output1 As integer, Output2 As Integer
Input1 = 1
Input2 = 2
Ret = Test(Input1, Input2, Output1, Output2)
Sheet1.Range("A1") = Ret ' 2
Sheet1.Range("A2") = Output1 ' 3
Sheet1.Range("A3") = Output2 '-1
End Sub
答案 5 :(得分:2)
不优雅,但如果您不重复使用您的方法,您还可以使用全局变量,这些变量由代码开头的Public语句定义,在Subs之前。 但是,您必须谨慎,一旦您更改了公共值,它将在您的代码中保存在所有子和函数中。
答案 6 :(得分:2)
您可以将2个或更多值返回给VBA中的函数或任何其他可视化基础的东西,但您需要使用名为Byref的指针方法。请参阅下面的示例。我将创建一个函数来添加和减去2个值,例如5,6
sub Macro1
' now you call the function this way
dim o1 as integer, o2 as integer
AddSubtract 5, 6, o1, o2
msgbox o2
msgbox o1
end sub
function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
sum = a + b
dif = b - 1
end function
答案 7 :(得分:1)
我总是通过总是返回ArrayList
来从函数返回多个结果。使用ArrayList
我只能返回一个由多个值组成的项目,在Strings
和Integers
之间混合。
在我的主要子组中返回ArrayList
之后,我只使用ArrayList.Item(i).ToString
,其中i
是我想要从ArrayList
<返回的值的索引/ p>
一个例子:
Public Function Set_Database_Path()
Dim Result As ArrayList = New ArrayList
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.RestoreDirectory = True
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.Multiselect = False
If fd.ShowDialog() = DialogResult.OK Then
Dim Database_Location = Path.GetFullPath(fd.FileName)
Dim Database_Connection_Var = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & Database_Location & """"
Result.Add(Database_Connection_Var)
Result.Add(Database_Location)
Return (Result)
Else
Return (Nothing)
End If
End Function
然后像这样调用函数:
Private Sub Main_Load()
Dim PathArray As ArrayList
PathArray = Set_Database_Path()
My.Settings.Database_Connection_String = PathArray.Item(0).ToString
My.Settings.FilePath = PathArray.Item(1).ToString
My.Settings.Save()
End Sub
答案 8 :(得分:0)
您可以将所需的所有数据从文件连接到单个字符串,并在Excel工作表中将文本分隔为列。 这是我为同样的问题做的一个例子,享受:
Sub CP()
Dim ToolFile As String
Cells(3, 2).Select
For i = 0 To 5
r = ActiveCell.Row
ToolFile = Cells(r, 7).Value
On Error Resume Next
ActiveCell.Value = CP_getdatta(ToolFile)
'seperate data by "-"
Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Cells(r + 1, 2).Select
Next
End Sub
Function CP_getdatta(ToolFile As String) As String
Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True
Range("A56000").Select
Selection.End(xlUp).Select
x = CStr(ActiveCell.Value)
ActiveCell.Offset(0, 20).Select
Selection.End(xlToLeft).Select
While IsNumeric(ActiveCell.Value) = False
ActiveCell.Offset(0, -1).Select
Wend
' combine data to 1 string
CP_getdatta = CStr(x & "-" & ActiveCell.Value)
ActiveWindow.Close False
End Function