我從來沒有在VBA中使用全局變量,但我知道全局變量是在函數/子聲明之外實例化的嗎?訪問VBA中的全局變量(Excel)
我有一個全局(公共)變量聲明在模塊的頂部,然後由同一模塊內的子例程賦予值0。每當打開工作簿
Option Explicit
Public NumNodes As Integer
Sub Inst_Glob_Vars()
NumNodes = 0
End Sub
該子程序被調用(子被稱爲在「的ThisWorkbook」對象),這也將實例全局變量和設定值0。
Option Explicit
Private Sub Workbook_Open()
Call Inst_Glob_Vars
End Sub
我在excel表單中有一個按鈕,單擊它時會增加這個全局變量。此按鈕的定義位於Sheet1對象中。
Private Sub CommandButton2_Click()
'NumNodes = NumNodes + 1
Debug.Print "NumNodes = " & NumNodes 'Debug
End Sub
我需要每一個模塊中聲明全局/公共變量/使用變量對象?每次點擊按鈕,變量都不會遞增,但在調試時會給出一個空/空值。我肯定沒有正確地聲明我的全局變量,但不知道我在哪裏犯錯誤。
更新:這裏是更新的命令按鈕子。如果我註釋掉第二個子調用(Node_Button_Duplication),一切正常。機會是它可能是子,這是造成問題...
Private Sub CommandButton2_Click()
Call Channel_Selection_Duplication
Call Node_Button_Duplication
NumNodes = NumNodes + 1
Debug.Print "NumNodes = " & NumNodes 'Debug
End Sub
兩個Channel_Selection_Duplication和Node_Button_Duplication都是相同的獨立模塊中定義:
Option Explicit
Public Sub Channel_Selection_Duplication()
'
' Description: Macro which duplicates the 'Channel Usage Selection' columns at a specific cell reference
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
'NumNodes = NumNodes + 1
'Debug.Print NumNodes
End Sub
Public Sub Node_Button_Duplication()
ActiveSheet.Shapes("CommandButton1").Select
Selection.Copy
Range("Q5").Select
ActiveSheet.Paste
Selection.ShapeRange.IncrementTop -14.25
End Sub
你必須申報一次。你可以在任何模塊中完成:)請向我們展示代碼。同時向我們展示如何增加變量? –