我有一个sub,我每次运行它的时候都会得到值。例如,我在sub中有x,a,b,c变量。
假设sub运行了4次,每次运行时,x都会得到以下值: 1. "5“2. "2”3. "7“4. "11”
X将值转发给a。a、b和c写入一个单元格,结果应为|5||-||-|
在第二次运行时,b应该得到a的值,a应该得到新x的值。然后我们得到结果:|2||5||-|
第三次运行时,我们还有一个c:|7||2||5|
第四:| 11 ||7||2
从逻辑上讲,这可以通过c = b,b= a,a= x;cell =a&b&c来解决。
然而,结果却是无稽之谈。
代码:
Sub getpingms_switch_Click()
Dim x As Integer: Dim y As Integer
Dim c As Range
Dim p1 As String
Dim p2 As String
Dim p3 As String
Dim ms As String
p2 = "*"
p3 = "*"
For Each c In Sheets("Topology").UsedRange.Cells
If c.Value = "Switch$" Then
y = c.Column + 1: x = c.Row + 2
DoEvents
Do Until IsEmpty(Cells(x, y)) 'IsEmpty is a function that stops the Do Until when the cell is empty
If Left(Cells(x, y), 7) = "172.21." Then
ms = sPing(Cells(x, y)) 'sPing gets the ms of the pinged pc
p3 = p2
p2 = p1
p1 = ms
Cells(x, y + 1) = p1 & " ms " & "| " & p2 & "ms | " & p3 & " ms"
If p1 = "timeout" Then
Cells(x, y + 1).Interior.ColorIndex = "3"
ElseIf p1 < 16 And p1 > -1 Then
Cells(x, y + 1).Interior.ColorIndex = "4"
ElseIf p1 > 15 And p1 < 51 Then
Cells(x, y + 1).Interior.ColorIndex = "6"
ElseIf p1 > 50 And p1 < 4000 Then
Cells(x, y + 1).Interior.ColorIndex = "45"
Else
Cells(x, y + 1).Interior.ColorIndex = "15"
End If
End If
x = x + 1
Loop
End If
Next c
End Sub从技术上讲,我在第一次运行后得到以下结果:
“18 ms | ms |* ms”
“1 ms |18 ms| ms”
-
“1毫秒| 1ms | 18毫秒”
“24 ms | 1ms |1 ms”
-
“1毫秒| 24ms |1毫秒”
“1毫秒| 1ms | 24毫秒”
“2毫秒| 1ms |1毫秒”
-
“2 ms |2 ms|1 ms”
“1 ms |2 ms|2 ms”
-
“1 ms | 1ms |2 ms”
“1 ms | 1ms |1 ms”
-
“1 ms | 1ms |1 ms”
“1 ms | 1ms |1 ms”
“1 ms | 1ms |1 ms”
-
“51毫秒| 1ms |1毫秒”
“1毫秒|51毫秒|1毫秒”
-
-
“0毫秒| 1ms | 51毫秒”
“0毫秒| 0ms |1毫秒”
我们怎么解决这个问题呢?
发布于 2014-08-27 08:59:16
您需要的是在模块范围内声明的static变量。只要代码运行,静态变量就会保持它们的值不变。
Private Static variable As Integer
Private Sub Counter()
variable = variable + 1
End Sub
Public Sub Main()
Dim i as Integer
For i = 0 To 10
Counter
MsgBox variable
Next
End Sub每次执行此代码时,它都会递增变量计数器。
现在,如果你不打算在循环中运行你的函数,而是想通过按钮点击来实现,那么当代码运行完成时,静态变量就会丢失它的值。在这种情况下,我建议将中间值存储在隐藏的工作表中。
如果你想变得更花哨,你可以添加一个对Access的引用,并使用TempVar来完成同样的事情。
https://stackoverflow.com/questions/25516345
复制相似问题