In my code, I have a combobox on a userform. The user selects an option from the drop down and the userform sets the selected value to a global variable "monthYearEntered".
Then i have a sub routine that uses the global variable. However, the value of the global variable is not carrying over to the subroutine. I know because I made a MsgBox of the variable from within the userform and then again in the sub routine. I get the right value in the form but not the routine.
I researched a bit and saw some potential solutions but none of them worked for me. In some past codes, I made a workaround by setting cell to the value and then referencing the cell to set the variable in the subroutine. I would like to avoid that since its just a Band-Aid.
USERFORM CODE
Private Sub CBN_OK_Click()
If YearMonthField = "" Then
MsgBox "Value cannot be blank. Please enter correct value."
Exit Sub
Else
monthYearEntered = YearMonthField.Value
MsgBox monthYearEntered
Me.Hide
Application.Run "DeleteMonth"
End If
End Sub
MODULE
Option Explicit
Dim monthYearEntered As String
Private Sub RangetoDelete()
Application.DisplayAlerts = False
Dim ws As Worksheet
Dim tableSalesCombined As ListObject
Dim cell, rng As Range
Set ws = ThisWorkbook.Worksheets("Sales Data Combined")
Set tableSalesCombined = ws.ListObjects("Table_SalesCombined")
Set rng = ws.Columns("I:I")
DeleteMonthForm.Show 'show user form
'monthYearEntered.ClearContents
Application.Run "Protect"
Application.DisplayAlerts = True
End Sub
Private Sub DeleteMonth()
Application.DisplayAlerts = False
Dim ws As Worksheet
Dim tableSalesCombined As ListObject
'Dim monthYearValue
Dim cell, rng As Range
Set ws = ThisWorkbook.Worksheets("Sales Data Combined")
Set tableSalesCombined = ws.ListObjects("Table_SalesCombined")
Set rng = ws.Columns("I:I")
ws.Unprotect Password:=PassW
'look for value entered by user (monthYearValue)
Set cell = rng.Find(What:=monthYearEntered, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)
MsgBox monthYearEntered
If cell Is Nothing Then
MsgBox monthYearEntered & "not found in Combined Sales Data. Please confirm value and try again."
Exit Sub
End If
With tableSalesCombined
.Range.AutoFilter Field:=9, Criteria1:=monthYearEntered
If Not .DataBodyRange Is Nothing Then
'.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
End If
'.Range.AutoFilter
End With
tableSalesCombined.AutoFilter.ShowAllData
'monthYearEntered.ClearContents
Application.Run "Protect"
Application.DisplayAlerts = True
End Sub
Public monthYearEntered As StringMsgBox monthYearEnteredgive you? Are you usingOption Explicitin all your code modules?