[英]Using a variable's value from one sub into another in VBA
Please, I am trying to use a variable's value from one sub into another, but unfortunately I did not get it. 拜托,我正在尝试将变量的值从一个子对象转换为另一个子对象,但不幸的是我没有得到它。 Follow the code below: 请遵循以下代码:
Sub get_value()
Dim area2 As Range
Set area2 = Range(Cells(8, 2), Cells(linha, 2))
f = area2.Count
s = x - f
End Sub
Sub get_value_s()
Worksheets(2).Activate
Range("A3").Select
Selection.End(xlDown).Select
linha = Selection.Row
linha2 = linha + s
Rows(linha2).Select
Selection.Insert Shift:=xlDown
End Sub
PS I have set s as integer globally. PS我已将s全局设置为整数。 (Public s As Integer). (以整数形式公开)。
Many thanks! 非常感谢!
It's hard to know what the error is without more code since you have several other global variables and we can't see how they are set. 没有更多的代码,很难知道错误是什么,因为您还有其他几个全局变量,而我们看不到它们的设置方式。 My guess is that your not setting your variables before your calling them. 我的猜测是您在调用变量之前未设置变量。 For example, are you sure get_value()
is called before get_value_s()
and that x
& linha
are the correct values at the time you call it? 例如,您确定get_value()
调用get_value_s()
之前先调用get_value_s()
,并且x
和linha
在您调用时是正确的值吗?
I'd suggest not using Globals unless you really have too. 我建议不要使用Globals,除非您确实有。 I can get your code down to only one global ( x
) and this is because I have no info on where this comes from. 我可以将您的代码简化为仅一个全局( x
),这是因为我没有有关其来源的信息。
Try this instead: 尝试以下方法:
Public x As Integer
Function get_value(linha As Integer, wks As Worksheet)
Dim area2 As Range
Set area2 = wks.Range(Cells(8, 2), Cells(linha, 2))
Dim f As Long
f = area2.Count
get_value = x - f
End Function
Sub get_value_s()
Dim wks As Worksheet
Set wks = Worksheets(2)
Dim linha As Integer, linha2 As Integer
linha = wks.Range("A3").End(xlDown).Row
linha2 = linha + get_value(linha, wks)
wks.Rows(linha2).Insert Shift:=xlDown
End Sub
And make sure X
is set before you call get_value_s
! 并确保在调用get_value_s
之前设置了X
!
Like what Portland Runner suggested, you can do it like this. 就像Portland Runner的建议一样,您可以这样做。
Function get_value()
Dim area2 As Range
Set area2 = Range(Cells(8, 2), Cells(linha, 2))
f = area2.Count
get_value = x - f
End Function
Sub get_value_s()
Worksheets(2).Activate
Range("A3").Select
Selection.End(xlDown).Select
linha = Selection.Row
linha2 = linha + get_value()
Rows(linha2).Select
Selection.Insert Shift:=xlDown
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.