excel vba给下一个variables赋值

每次运行它时,我都会得到一个值。 我想要做的是每次运行子程序时向另一个添加一个variables。 例如,我在子里面有x,a,b,cvariables。

可以说子运行4次,每次运行,x得到以下值:1.“5”2.“2”3.“7”4.“11”

x给予a的值。 a,b和c写入单元格,结果应该是| 5 | | – | | – |

在第二次运行时,b应该得到a和a的值应该得到新x的值。 比我们得到的结果:| 2 | | 5 | | – |

第三轮,我们也有交stream:| 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”

“1ms | 18ms | ms”

“1 ms | 1ms | 18 ms”

“24 ms | 1ms | 1 ms”

“1毫秒| 24毫秒| 1毫秒”

“1 ms | 1ms | 24 ms”

“2 ms | 1ms | 1 ms”

“2 ms | 2ms | 1 ms”

“1 ms | 2ms | 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毫秒| 1毫秒| 1毫秒”

“1毫秒| 51毫秒| 1毫秒”

“0毫秒| 1毫秒| 51毫秒”

“0 ms | 0ms | 1 ms”

我们怎么解决这个问题?

编辑:我想出了为什么我得到这些结果,但我不知道如何能解决这个问题。

你想要的是在模块范围声明的静态variables。 只要代码正在运行,静态variables就会保留它们的值。

 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 

每次你执行这个代码,它都会增加variables计数器。

现在,如果你不打算在一个循环中运行你的函数,而是说,想通过button点击来完成这个工作,那么静态variables在代码运行完毕后将失去它的值。 在这种情况下,我build议将中间值存储在隐藏的工作表中。

如果你想变得花哨,你可以添加一个Access的引用,并使用TempVar来完成同样的事情。