防止从excel重新编译中重置VBA变量

时间:2012-05-15 20:09:11

标签: excel vba excel-vba

Private Sub CommandButton2_Click()

Dim TempVar As Integer

TempVar = NumNodes
NumNodes = NumNodes + 1
TempVar = NumNodes
Debug.Print "NumNodes + 1"

Call Node_Button_Duplication
Call Channel_Selection_Duplication

NumNodes = TempVar

Debug.Print "NumNodes = " & NumNodes 'Debug
Debug.Print "TempVar = " & NumNodes 'Debug
End Sub

Public Sub Channel_Selection_Duplication()

    Range("Q8:S8").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge
    Range("Q8:S8").Select
    ActiveCell.FormulaR1C1 = "Channel Usage Selection"
    Range("Q8:S52").Select
    Range("Q52").Activate
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = xlAutomatic
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = xlAutomatic
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = xlAutomatic
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = xlAutomatic
    End With
    With Selection.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
Range("Q8:S8").Select
Selection.Interior.ColorIndex = 36

End Sub

Public Sub Node_Button_Duplication()


Worksheets("Topology").Shapes("CommandButton1").Select
Selection.Copy
Worksheets("Topology").Paste
Selection.ShapeRange.IncrementLeft 339#
Selection.ShapeRange.IncrementTop -12.75

End Sub

我正在尝试在调用2个子例程(Node_Button_Duplication和Channel_Selection_Duplication)之前保存NumNodes(全局变量)的值,第一个子例程称为复制并粘贴电子表格中的命令按钮。我相信,这会重新编译VBA项目并重置(所有?)全局变量。

我曾尝试写入单元格并从单元格中读回值,但这不起作用(基本上与使用临时变量的想法相同)。

上面的代码在运行时会导致每次运行时TempVar和NumNodes都重置为1。我想知道保存变量不被重置的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个

Option Explicit

Private Sub CommandButton2_Click()
    Dim NumNodes as Long

    NumNodes = Sheets("Temp").Range("A1").Value

    NumNodes = NumNodes + 1

    Sheets("Temp").Range("A1").Value = NumNodes

    MsgBox "NumNodes = " & NumNodes

    Call Node_Button_Duplication
    Call Channel_Selection_Duplication
End Sub

确保您有一张名为“Temp”的工作表

现在尝试一下。