如何让 excel vba 中的子程序变成 return 的东西?
how to get a subroutine in excel vba to return something?
我在 excel vba 中有以下代码:
Sub main()
Call Get_Rows_Generic("usersFullOutput.csv", 1)
End Sub
在另一个模块中我有:
Sub Get_Rows_Generic(work_sheet As String, column_num As Integer)
Dim wsUsers As Worksheet: Set wsUsers = Worksheets(work_sheet)
Dim userRows As Integer: userRows = wsUsers.Cells(Rows.Count, column_num).End(xlUp).Row
MsgBox userRows
End Sub
我如何在子 Get_Rows_Generic
之外访问子 Get_Rows_Generic
的结果(MsgBox
中显示的内容)?即将结果输入另一个子单元或单元格...等等
那为什么不把它变成一个函数呢?
Function Get_Rows_Generic(work_sheet As String, column_num As Integer)
Dim wsUsers As Worksheet: Set wsUsers = Worksheets(work_sheet)
Dim userRows As Integer: userRows = wsUsers.Cells(Rows.Count, column_num).End(xlUp).Row
Get_Rows_Generic = userRows
End Sub
那么你的电话可以是
Sub main()
Dim result as integer
result = Get_Rows_Generic("usersFullOutput.csv", 1)
End Sub
如果您希望 result
成为全局变量,那么我会向您推荐这个问题:How do I declare a global variable in VBA?
Public result as integer
假设您知道可以将 Sub 转换为函数,那么有一种粗略的方法可以实现您想要做的事情。由于 VBA/VBScript 默认情况下将参数作为 ByRef
传递,您可以将其用于 "return" 一个值。
Sub main()
Dim userRows as Integer
userRows = 0
Call Get_Rows_Generic("usersFullOutput.csv", 1, userRows)
Msgbox userRows
End Sub
Sub Get_Rows_Generic(work_sheet As String, column_num As Integer, ByRef userRows as Integer)
Dim wsUsers As Worksheet: Set wsUsers = Worksheets(work_sheet)
Dim userRows As Integer: userRows = wsUsers.Cells(Rows.Count, column_num).End(xlUp).Row
End Sub
我在 excel vba 中有以下代码:
Sub main()
Call Get_Rows_Generic("usersFullOutput.csv", 1)
End Sub
在另一个模块中我有:
Sub Get_Rows_Generic(work_sheet As String, column_num As Integer)
Dim wsUsers As Worksheet: Set wsUsers = Worksheets(work_sheet)
Dim userRows As Integer: userRows = wsUsers.Cells(Rows.Count, column_num).End(xlUp).Row
MsgBox userRows
End Sub
我如何在子 Get_Rows_Generic
之外访问子 Get_Rows_Generic
的结果(MsgBox
中显示的内容)?即将结果输入另一个子单元或单元格...等等
那为什么不把它变成一个函数呢?
Function Get_Rows_Generic(work_sheet As String, column_num As Integer)
Dim wsUsers As Worksheet: Set wsUsers = Worksheets(work_sheet)
Dim userRows As Integer: userRows = wsUsers.Cells(Rows.Count, column_num).End(xlUp).Row
Get_Rows_Generic = userRows
End Sub
那么你的电话可以是
Sub main()
Dim result as integer
result = Get_Rows_Generic("usersFullOutput.csv", 1)
End Sub
如果您希望 result
成为全局变量,那么我会向您推荐这个问题:How do I declare a global variable in VBA?
Public result as integer
假设您知道可以将 Sub 转换为函数,那么有一种粗略的方法可以实现您想要做的事情。由于 VBA/VBScript 默认情况下将参数作为 ByRef
传递,您可以将其用于 "return" 一个值。
Sub main()
Dim userRows as Integer
userRows = 0
Call Get_Rows_Generic("usersFullOutput.csv", 1, userRows)
Msgbox userRows
End Sub
Sub Get_Rows_Generic(work_sheet As String, column_num As Integer, ByRef userRows as Integer)
Dim wsUsers As Worksheet: Set wsUsers = Worksheets(work_sheet)
Dim userRows As Integer: userRows = wsUsers.Cells(Rows.Count, column_num).End(xlUp).Row
End Sub