Forgive my trivial question, but I am a total newbie when it comes to VBA. I am just starting and I came up with this code after lots of reading and trial and error, although probably not the most efficient one.
I have this code pasted in Worksheet1 and Worksheet2 with a CommandButton1 on each one to fire the code. What I am trying to do is to have a single CommandButton1 that would fire the code though all the specified sheets, instead of having to go to each sheet and hit the button each time.
Lastly, is there a way to dynamically populate? Right now, I am telling to put the value for lngSelect1 and lngSelect2 in a specific cell (H17 and H18). The problem is that I have about 500 values to return and if there are any changes, I have to manually slide everything. Could I set the first values (for lngSelect1) and have VBA return all the others one cell/row down?
Thanks for your help
[vba]Option Explicit
Dim glngDataTotalRows As Long
Private Sub CommandButton2_Click()
Application.EnableEvents = False
Sheets(Array("Sheet1", "Sheet2")).PrintPreview
Application.EnableEvents = True
End Sub
Private Sub CommandButton1_Click()
glngDataTotalRows = lngLastRow
UpdateDataTable
MsgBox "The report is ready"
End Sub
Private Function lngLastRow() As Long
Dim lngDataTotalRows As Long
lngDataTotalRows = 1
Do Until Worksheets(strDataTab).Cells(lngDataTotalRows, 1).Value = ""
lngDataTotalRows = lngDataTotalRows + 1
Loop
lngLastRow = lngDataTotalRows - 1
End Function
Private Function blnIsRegion(lngRowIndex As Long)
If Worksheets(strDataTab).Cells(lngRowIndex, 2).Value = Worksheets(Me.Name).Range("H15").Value Then
blnIsRegion = True
Else
blnIsRegion = False
End If
End Function
Private Function blnIsDivision(lngRowIndex As Long)
If Worksheets(strDataTab).Cells(lngRowIndex, 3).Value = Worksheets(Me.Name).Range("H15").Value Then
blnIsDivision = True
Else
blnIsDivision = False
End If
End Function
Private Function blnIsState(lngRowIndex As Long)
If Worksheets(strDataTab).Cells(lngRowIndex, 37).Value = Worksheets(Me.Name).Range("H15").Value Then
blnIsState = True
Else
blnIsState = False
End If
End Function
Private Sub Worksheet_Activate()
End Sub
Private Function strDataTab() As String
strDataTab = Me.Name & "-Data"
End Function
Private Sub UpdateDataTable()
Dim lngRowIndex As Long
Dim lngSelect1 As Long,
Dim lngSelect2 As Long,
For lngRowIndex = 2 To glngDataTotalRows
If blnIsRegion(lngRowIndex) = True Or blnIsDivision(lngRowIndex) = True Or blnIsState(lngRowIndex) = True Then
Select Case Worksheets(strDataTab).Cells(lngRowIndex, 3).Value
Case "ABC"
lngSelect1 = lngSelect1 + 1
Case "DEF"
lngSelect2 = lngSelect2 + 1
End Select
End If
Next
'Populate
Worksheets(Me.Name).Range("H17").Value = lngSelect1
Worksheets(Me.Name).Range("H18").Value = lngSelect2
[/vba]