2015-11-19 65 views
0

我已经通过了约。 20个类似的问题,我不能链接所有,但不幸的是没有能够外推的信息解决我的问题:将int/var传递给vba中的另一个模块

如何将一个整数(或字符串)从模块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: 呼叫process3(A,B)

和定义一个朦胧..和暗淡b ..外/上述子进程2

回答

-1

这是,如预期的语法问题,很显然,如果你想传递的一个子变量一定的模块中,你还需要告诉擅长认为这些变量,因此,成功的结果看起来像:

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 

请注意,变量需要传递的原因是由于编程效率低下,代码在第一次过程中第二次变得太长。希望这有助于未来的任何人。

+0

除非变量是全球性的或公共的,是怎么回事,他们会进入process3()? –

+0

在状态我在的时候,不知道有什么这种差异,全球性,公众之间,以及非全局/非公开,我认为,那一刻变量创建somehwere数字框的记忆里,它将在需要时从该数字位置提取。 如前所述,appearently它是更方便地创造一个变量包含在除非另有说明,单独的领域。感谢您的帮助和关心。 –

0

我看到你的答案有,但我认为你可能有一个关于这个语法是如何工作的误解:

的关键是,你是一个已知类型的变量的值传递给其他子,但的变量是不一样的;并且它们不需要相同的名称。这可以让你的被调用的subs被更广义化 - 他们可以根据它们被调用的位置对不同的变量执行相同的例程。看下面的一个例子来扩展这个概念。

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 

看到,在过程1 VS过程2,参数被作为不同的项目通过,但process3参考这些项目转换成简单的“a”和“B”。这是一个非常重要的区别 - 这意味着无论你对process3中的一个& b做什么都不会改变传递给它的初始变量。请注意,在process3中设置b = 0的情况下,这只是一个毫无意义的陈述,因为在process3结束时,变量b将不再存在。

如果你想拥有'通用'变量,多个潜艇可以随意改变,你将需要它们成为全局变量(更多信息请参考其他地方)简而言之,全局变量不会被'擦除'完成给定的子程序,它们存储在内存中,而工作簿保持打开状态)。

还请注意,我指定的参数“A”,“B”和“海峡”传递“BYVAL”。这意味着我没有传递原始实际变量,我正在传递该变量的值。