具有 Call 函数的公共变量

具有 Call 函数的公共变量

我尝试找出错误所在,已经花了两个小时在 Google 上搜索它 :(

我创建了数组 (ArrayTestPrime),其中包含以下元素:变量、数组和 4 个数字。我将其声明在所有“Subs”之上,因此它必须在整个模块中可见。

我只想在第一个过程中更改数组 (ArrayTestPrime) 中元素 (0) 的值,然后打印它。然后调用 Procedure_2 打印它,然后在工作表 (1) 的第 1 行中循环并再次更改它。

调试。打印显示以下内容:

 First_Procedure =  

 At the beginning of Second_Procedure =  

 Variable must be equal =  17

 At the end of Second_Procedure =  

但真正的价值观必须是:

 First_Procedure =  100

 At the beginning of Second_Procedure =  100

 Variable must be equal =  17

 At the end of Second_Procedure =  17

让我头脑风暴的代码:

Public Article As String
Public ArticleCol As Variant
Public ArrayTestPrime As Variant
Public ArrayInArray() As Variant

Sub First_Procedure()
Article = "ARTICLE"
ArrayTestPrime = Array(ArticleCol, ArrayInArray(), 1, 2, 2, 1)
ArticleCol = 100
Debug.Print "First_Procedure =  " & ArrayTestPrime(0)

Call Second_Procedure

End Sub


Sub Second_Procedure()

Dim Sub_J As Integer
Debug.Print "At the beginning of Second_Procedure =  " & ArrayTestPrime(0)

 For Sub_J = 1 To 27
    If Cells(1, Sub_J) = Article Then ArticleCol = Sub_J
 Next Sub_J

 Debug.Print "Variable must be equal =  " & ArticleCol
 Debug.Print "At the end of Second_Procedure =  " & ArrayTestPrime(0)
 End Sub

请帮助我!我会感激任何帮助!

答案1

您的变量分配有两个问题......

1)您已通过以下代码翻转了订单:

  Sub First_Procedure()
  Article = "ARTICLE"
→ ArrayTestPrime = Array(ArticleCol, ArrayInArray(), 1, 2, 2, 1)  'ArticleCol = "" 
→ ArticleCol = 100
  Debug.Print "First_Procedure =  " & ArrayTestPrime(0)  'ArticleCol = ""

它应该是:

   Sub First_Procedure()
   Article = "ARTICLE"
 → ArticleCol = 100
 → ArrayTestPrime = Array(ArticleCol, ArrayInArray(), 1, 2, 2, 1)  'ArticleCol = 100
   Debug.Print "First_Procedure =  " & ArrayTestPrime(0)  'ArticleCol = 100

2)您忘记设置ArrayTestPrime(0)的值:

   For Sub_J = 1 To 27
      If Cells(1, Sub_J) = Article Then ArticleCol = Sub_J
   Next Sub_J

 → ArrayTestPrime(0) = ArticleCol  'We must set our new value for ArrayTestPrime(0)

   Debug.Print "Variable must be equal =  " & ArticleCol
   Debug.Print "At the end of Second_Procedure =  " & ArrayTestPrime(0)
   End Sub

相关内容