如何在excel VBA中的宏中的多个子中使用单个变量 [英] How to use a single variable in multiple subs in a macro in excel VBA

查看:384
本文介绍了如何在excel VBA中的宏中的多个子中使用单个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个分为2个潜艇的宏。



用户界面有2个按钮,每个按钮分配给一个子。



我的查询在第一个子,有一个计算,假设它给出x = 2。在第二个子程序中,我需要检查x的值。



我不能从另一个sub中调用一个sub,因为它们是通过不同的按钮点击工作的。



编辑:

点击第一个按钮,用户将浏览文件,文件计数将存储在x中。

开第二个按钮点击,将检查是否x> 0.

用户可以在点击第一个按钮后等待一段时间。或者可以改变文件的数量。



因此除了变量x之外,subs是互相排斥的。



怎么做?

谢谢.. !!



我尝试过:



1.Dim x As Integer

在所有潜艇之外。但它没有保留价值。



2.我试图使用功能,但这并没有让我任何地方!

解决方案

在子/函数之外它不是Dim ..使用私有或公共为你的领域。



无论如何,...肯定你可以打电话给另一个sub / function



私有数据为整数

公共子a()
数据= 5
电话b
结束次级

公共子b()
MsgBox数据是:&数据
End Sub


如果要定义全局变量,请插入新模块并以此方式声明:

  Public  xSharedValue  As   Integer  





但是...



你可以打电话另一个来源:

 私人  Sub  Button1_Click 
' 此处的代码
' ....

' 调用另一个子/过程
DoSomething(x)
结束 Sub

私有 Sub DoS omething( ByVal x 作为 整数
' 此处的代码
结束 Sub





如果 DoSomething 程序在不同的模块中,您必须将其声明更改为:

  私人  公共  Sub  DoSomething( ByVal  x 作为 整数
' 您的代码
结束 Sub





详情请见: Visual Basic for Applications中的变量范围 [ ^ ]


Hi All,

I have a macro that is divided into 2 subs.

The user interface has 2 buttons, each assigned to a sub.

My query is in the first sub, there is a calculation, suppose it gives x=2. In the second sub i need to check the value of x.

I can't call one sub from another as they work from different button click.

Edit:
On first button click, user will browse files and the file count will be stored in x.
On second button click, there will be a check if x > 0.
User can wait for sometime after clicking first button. Or can change the no of files.

So subs are exclusive of each other except the variable x.

How to do that??
Thank you..!!

What I have tried:

1. "Dim x As Integer"
outside all subs. But it does not retain the value.

2. I tried to use function but that did not get me anywhere!!

解决方案

outside a sub/function its not Dim .. use Private or Public for your field.

anyway,.. sure u can call another sub/function

Private Data As Integer

Public Sub a()
    Data = 5
    Call b
End Sub

Public Sub b()
    MsgBox "Data is: " & Data
End Sub


If you want to define global variable, insert new module and declare it this way:

Public xSharedValue As Integer



But...

You can call one sub from another:

Private Sub Button1_Click
    'your code here
    '....
    
    'call another sub/procedure
    DoSomething(x)
End Sub

Private Sub DoSomething(ByVal x As Integer)
    'your code here
End Sub



If a DoSomething procedure is in a different module, you have to change its declaration to:

Private Public Sub DoSomething(ByVal x As Integer)
    'your code here
End Sub



For further details, please see: Scope of variables in Visual Basic for Applications[^]


这篇关于如何在excel VBA中的宏中的多个子中使用单个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆