【问题标题】:Excel-VBA - Call Sub and ask it to regconise variable defined outside the SubExcel-VBA - 调用 Sub 并要求它识别在 Sub 之外定义的变量
【发布时间】:2011-04-25 02:52:22
【问题描述】:

我试图从我的程序 callLum() 中调用 sub Lum(),要求 Lum 分别获取值 11、12、13,但似乎 Lum 无法识别我之前在 callLum 中对计数器的定义(),如下图所示。原因是在我的实际主脚本中,我有一个很长的 For-next 循环,如果我不使用 Msgbox 中断循环,程序在到达“next”时似乎找不到“For”字。这就是为什么我最终结束了主脚本,然后创建了一个简单的子脚本来调用它。

Sub callLum()
  Dim counter As Integer
  Dim LR As Long, j As Long

  counter = 10
  'checking number of rows in column A
  LR = Range("A" & Rows.Count).End(xlUp).Row

  For j = 1 To LR
   If Not IsEmpty(Range("A" & j)) And Not IsEmpty(Range("B" & j)) Then _
     counter = counter + 1        
   Call Lum                                                            
  Next j
  MsgBox "THE END"
End Sub


Sub Lum()
  MsgBox "Counter value is " & counter
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    将 Lum 更改为:

    Sub Lum(ByVal counter as Integer)
       MsgBox "Counter value is " & counter
    End Sub
    

    对于您的循环,与其分别测试范围的每个元素,不如将范围指定为 Ax:Ay,其中 x 和 y 由您的循环填充。

    【讨论】:

    • 它起作用了,当我在 callLum sub 中将“call Lum”更改为“call Lum (byval counter)”时,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 2012-01-06
    • 2023-03-21
    • 2019-09-04
    • 2013-11-30
    • 2017-01-25
    • 2019-04-12
    • 2013-08-09
    相关资源
    最近更新 更多