我在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
(MsgBox
中显示的内容)的结果?即将结果输入另一个子或单元......等等。
答案 0 :(得分:3)
为什么不让它成为一个功能呢?
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
答案 1 :(得分:1)
假设您知道可以将Sub转换为函数,那么有一种粗略的方法可以实现您的目标。由于VBA / VBScript默认情况下将参数传递为ByRef
,因此您可以使用它来“返回”一个值。
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