VBAでグローバル変数を使用したことはありませんが、グローバル変数が関数/サブ宣言の外部でインスタンス化されることを理解していますか?
モジュールの先頭でグローバル(パブリック)変数が宣言されており、同じモジュール内のサブルーチンによって値0が与えられています。
Option Explicit
Public NumNodes As Integer
Sub Inst_Glob_Vars()
NumNodes = 0
End Sub
このサブルーチンは、ワークブックが開かれるたびに呼び出され(subは「ThisWorkbook」オブジェクトで呼び出されます)、グローバル変数をインスタンス化して0の値を設定します。
Option Explicit
Private Sub Workbook_Open()
Call Inst_Glob_Vars
End Sub
エクセルシートにボタンがあり、クリックするとこのグローバル変数がインクリメントされます。このボタンの定義は、Sheet1オブジェクトにあります。
Private Sub CommandButton2_Click()
'NumNodes = NumNodes + 1
Debug.Print "NumNodes = " & NumNodes 'Debug
End Sub
変数が使用されるすべてのモジュール/オブジェクトでグローバル/パブリック変数を宣言する必要がありますか?ボタンをクリックするたびに、変数はインクリメントされませんが、デバッグ時にNull/Blank値が返されます。グローバル変数を正しく宣言していないことは確かですが、どこで間違いを犯しているのかはわかりません。
更新:これが更新されたコマンドボタンサブです。2番目のサブ呼び出し(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