Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 将int/var传递给vba中的其他模块_Excel_Vba - Fatal编程技术网

Excel 将int/var传递给vba中的其他模块

Excel 将int/var传递给vba中的其他模块,excel,vba,Excel,Vba,我已经浏览了大约20个类似的问题,我无法将它们全部链接起来,但不幸的是,我无法将这些信息外推到我的问题的解决方案中: 如何将一个整数(或字符串)从模块33子进程2移动到另一个模块34子进程3,以便在进程2中定义并编号该整数/字符串后,在模块33子进程2末尾调用后一个模块后,我可以简单地在模块34子进程3中使用 更具体地说,这是我的代码: sub process2() dim a as integer dim b as integer dim str as string a = 10 b = 3

我已经浏览了大约20个类似的问题,我无法将它们全部链接起来,但不幸的是,我无法将这些信息外推到我的问题的解决方案中:

如何将一个整数(或字符串)从模块33子进程2移动到另一个模块34子进程3,以便在进程2中定义并编号该整数/字符串后,在模块33子进程2末尾调用后一个模块后,我可以简单地在模块34子进程3中使用

更具体地说,这是我的代码:

sub process2()
dim a as integer
dim b as integer
dim str as string
a = 10
b = 3
str = stringname

call process3(a, str) 'line x
end sub

sub process3()
dim c as integer
c = a * 2 +b
msgbox(c)
end sub
我试过x行: 呼叫流程3(a、b)


以及定义dim a。。和暗淡的b。。子进程2的外部/上方

正如预期的那样,这是一个语法问题,显然,如果要从某个模块中的一个子进程传递变量,还需要告诉excel期望这些变量,因此成功的结果如下所示:

sub process2()
dim a as integer
dim b as integer
dim str as string
a = 10
b = 3
str = stringname

call process3(a, str) 'line x
end sub

sub process3(a, str)
dim c as integer
c = a * 2 +b
msgbox(c)
end sub

注意,需要传递变量的原因是,由于编程效率低下,代码在1个过程中第二次过长。希望这对将来的任何人都有帮助。

我在这里看到了您的答案,但我认为您可能对其语法有误解:

关键是您正在将一个已知类型的变量的值传递给另一个子变量,但变量不相同;而且它们不需要相同的名称。这使得被调用的sub更加通用化——它们可以使用不同的变量执行相同的例程,具体取决于调用它们的位置。请参阅下面的示例,该示例对该概念进行了扩展

sub process1()
    dim totalPies as integer
    dim totalCakes as integer
    dim str as string

    totalPies = 10
    totalCakes = 3
    str = "foo"

    call process3(totalPies, totalCakes, str)
    call process2 
end sub

sub process2()
    dim highCard as integer
    dim lowCard as integer
    dim str as string

    highCard = 10
    lowCard = 3
    strrrr = "bar"

    call process3(highCard, lowCard, strrrr)

end sub

sub process3(ByVal a as Integer, yVal b As Integer, ByVal str as String) 'adds 2 numbers and sends string to msgbox
    dim c as integer
    c = a * 2 + b
    b = 0
    msgbox(c&str)
end sub
请注意,在process1和process2中,参数作为不同的项传递,但是process3将对这些项的引用转换为简单的“a”和“b”。这是一个非常重要的区别-这意味着无论您在process3中对a&b做什么,都不会更改传递给它的初始变量。请注意,我在process3中设置b=0的地方,这只是一个无意义的语句,因为在process3的末尾,变量b将不再存在

如果您想拥有“通用”变量(多个子系统可以随意更改),则需要将它们设置为全局变量(请在其他地方查找以了解更多信息。简而言之,全局变量不会在给定子系统完成时“擦除”,而是在工作簿保持打开状态时存储在内存中)


还要注意,我指定参数“a”、“b”和“str”通过“ByVal”传递。这意味着我不是在传递原始的实际变量,而是在传递该变量的值。

除非变量是全局或公共的,否则它们如何进入process3()?在我当时不知道全局、公共和非全局/非公共之间存在任何差异的状态下,我假设,当变量在数字框内存中创建时,它将在需要时从该数字位置提取。如前所述,除非另有说明,否则创建包含变量的单独字段似乎更方便。谢谢你的帮助和关心。