Passing 1 of 3 values to a Sub

大城市里の小女人 提交于 2019-12-12 21:56:42

问题


I want to update a single (1 of 3) variable in a Sub.

The 3 variables have already been assigned, but I would like to update one of the variables.

See script below for a simple example of passing strings between subs in different Macros

In Macro1

Sub Sub1()

Text1 = "First Text"
Text2 = "Second Text"
Text3 = "Third Text"

Call Macro2.Sub2(Text1, Text2, Text3)

End Sub

In Macro2

Public PassedText1, PassedText2, PassedText3 As String
Sub Sub2(ByVal r1 As String, ByVal r2 As String, ByVal r3 As String)

PassedText1 = r1
PassedText2 = r2
PassedText3 = r3

End Sub
'=======================

I know I can create another sub in Macro2 where I can then pass a string and then assign it to the Public variable.

If there not another way?

I though of Something like:

Sub Sub3()

SomeText = "New Text"

Call Sub2(r1:=SomeText)

End Sub

回答1:


If you define your sub like this, you can use what you proposed :

Sub Sub2(Optional ByVal r1 As Variant, Optional ByVal r2 As Variant, Optional  ByVal r3 As Variant)

So, 2 changed things for each argument Optional ByVal r1 As Variant :

  1. Optional speaks for itself

  2. As Variant because you'll need to test is the argument is present in your call with the IsMissing() method, but for that the argument need to be defined as a Variant

So like this for the 3 arguments in your proc :

If Not IsMissing(r1) Then PassedText1 = r1


来源:https://stackoverflow.com/questions/33496517/passing-1-of-3-values-to-a-sub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!