【问题标题】:VBA pass variables between Sub and Public FunctionVBA 在 Sub 和 Public 函数之间传递变量
【发布时间】:2019-04-12 16:39:23
【问题描述】:

我是 VBA 新手,正在尝试将字符串从 Sub 传递给 Public Function(Sub 和 Public Function 在不同的模块中,但在同一个 Workbook 中),将字符串拆分为 Public Function 中的数组,然后将数组从 Public Function 传递回 Sub。

我已经搜索过 Stack Overflow 并尝试了几种不同的方法,但都没有奏效。以下是我目前拥有的代码,它会产生以下错误:

运行时错误“9”: 下标超出范围

任何帮助将不胜感激。为基本问题道歉。谢谢。

子:

Sub export()
Dim testString As String
Dim testValue As Variant

'testString could have any number of values
testString = "TEST1, TEST2, TEST3, TEST4"

'Call the Public Function below
testValue = splitText(testValue)

End Sub

在另一个模块中调用以下公共函数:

Public Function splitText() As Variant
Dim testValue As Variant

'Trying to import testString from the Sub to split it
testValue = Split(testString, ",")

'Define result of the Public Function
splitText = testValue

End Function

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    你需要使用一致的变量名并在函数调用中传递参数

    Public Sub export()
    
        Dim testString As String
        Dim testValue As Variant
    
        testString = "TEST1, TEST2, TEST3, TEST4"
    
        testValue = splitText(testString) '<== consistent naming and passed as argument 
    
    End Sub
    
    Public Function splitText(ByVal testString As String) As Variant '<== argument referenced in function signature
        Dim testValue As Variant
    
        testValue = Split(testString, ",") '<== consistent naming 
    
        splitText = testValue
    
    End Function
    

    【讨论】:

    • 非常感谢,它有效!为什么使用ByValtestString 传递给公共函数?我假设在公共函数名称将变量传递给函数之后将testString 放在括号中(这一行 - Public Function splitText(ByVal testString As String) As Variant)?
    • 这不是ByRef 的意思。 Object 是引用 type 的事实与 ByValByRef 没有任何关系。传递ByRef 意味着被调用的过程获得了在堆栈上传递的引用(基本上是指针)。这意味着被调用过程中的更改会传播回调用函数。它是Object 还是内在类型都没有关系。试试Sub Foo(ByRef bar As Object): Set bar = Nothing: End Sub,然后在调用过程中测试值...
    • 这个在section 5.3.1.11 of the VBA language spec有详细说明。
    • @Comintern 我并不是要暗示所有对象都通过 ByRef 传递,哎呀,但感谢您提供的附加信息。我会修改我的评论。
    • 绝对。在这种情况下,ByVal 应该用作显式合约,调用splitText 不会改变调用过程中testString 的值。我正在回复已删除的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2013-04-09
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多