Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/24.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 为什么可以';我能从模2中的公式中得到值吗?_Excel_Vba - Fatal编程技术网

Excel 为什么可以';我能从模2中的公式中得到值吗?

Excel 为什么可以';我能从模2中的公式中得到值吗?,excel,vba,Excel,Vba,我的excel VBA中有三个模块。我的主要计算是用模块1编写的,我想从模块2中调用SUB,如下所示(简化): 模块1: sub sub_a() 'some syntaks here call sub_b() sheet1.cells(1,1)=a end sub sub sub_a() 'some syntaks here call sub_b() sheet1.cells(1,1)=a end sub 模块2: sub sub_b() a=5 e

我的excel VBA中有三个模块。我的主要计算是用模块1编写的,我想从模块2中调用SUB,如下所示(简化):

模块1:

sub sub_a()

  'some syntaks here

  call sub_b()

sheet1.cells(1,1)=a

end sub
sub sub_a()

  'some syntaks here

  call sub_b()

sheet1.cells(1,1)=a

end sub
模块2:

sub sub_b()

   a=5

end sub
Global a as integer
sub sub_b()

   a=5

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

是的,您需要将“a”定义为全局变量。然后,它将对其他子例程可见。 例如:

模块1:

sub sub_a()

  'some syntaks here

  call sub_b()

sheet1.cells(1,1)=a

end sub
sub sub_a()

  'some syntaks here

  call sub_b()

sheet1.cells(1,1)=a

end sub
模块2:

sub sub_b()

   a=5

end sub
Global a as integer
sub sub_b()

   a=5

end sub

您的代码无法引用sub_b中设置的值,因为它是该sub_b的专用值

除了使用全局函数外,向调用者返回单个值的另一种方法是使用如下用户定义函数:

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
建议您使用函数构建代码,而不是跨任意子节点共享变量,因为如果您有一个大型应用程序,则很难跟踪变量的更改位置

函数还允许您传递参数


了解有关用户定义函数的详细信息。

您的
变量是否为全局变量?