为什么我不能从module2中的公式获取值到module1?

时间:2014-02-03 18:19:02

标签: excel vba

我的excel VBA中有三个模块。我的主要计算是在module1中编写的,我想从module2中调用subs(简化):

模块1:

sub sub_a()

  'some syntaks here

  call sub_b()

sheet1.cells(1,1)=a

end sub

模块2:

sub sub_b()

   a=5

end sub

问题是:为什么在sheet1.cells(1,1)中a值没有出来?怎么了?

2 个答案:

答案 0 :(得分:1)

是的,你需要定义" a"作为全球变量。然后它将对其他子程序可见。 E.G:

模块1:

sub sub_a()

  'some syntaks here

  call sub_b()

sheet1.cells(1,1)=a

end sub

模块2:

Global a as integer
sub sub_b()

   a=5

end sub

答案 1 :(得分:0)

您的代码无法引用sub_b中设置的值,因为它对该子类是私有的。

除了使用Global之外,另一种将单个值返回给调用者的方法是使用这样的用户定义函数:

Sub sub_a()
   ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Value = Fun_b 'the right-hand side is a function call to fun_b
End Sub

Function Fun_b() as Variant 'Specify the appropriate type to your needs
   a = 5
   Fun_b = a 'assign the result of execution here and return
End Function

建议您使用函数构建代码,而不是在任意子函数之间共享变量,因为如果您有大型应用程序,则很难跟踪变量的更改位置。

函数还允许您传递参数。

详细了解用户定义的函数here