This is what I did to make it work.
Tell me what you think and any suggestions to make it better.
Private Sub CommandButton1_Click()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet
Dim ws1rg As Range, ws3rg As Range, ws4rg As Range
Dim CarMeter(2 To 3534) As String
Dim i As Long, v As Long
Dim toCopyRange As Range
Dim ws3lastrow As Integer
Dim toCopyFinal As Range
Dim ws4lastrow As Integer
Dim EndDate As Date
Dim StartDate As Date
On Error GoTo Whoa ' if error, it will skip to next line of code (appropriate in this instance)
Application.ScreenUpdating = False
Set ws1 = Worksheets("Missing Dates")
Set ws2 = Worksheets("Car List")
Set ws3 = Worksheets("Workspace")
Set ws4 = Worksheets("Final")
Set ws1rg = ws1.Range("A1:C226703") 'defines ws1 range
Set ws3rg = ws3.Range("A:C")
ws1.AutoFilterMode = False
For i = 2 To 3534
ws3.AutoFilterMode = False
ws3.Cells.Clear
CarMeter(i) = ws2.Cells(i, 1)
lastRow = ws1.Cells(Rows.Count, 1).End(xlUp).Row
With ws1rg 'only applies to ws1rg
.AutoFilter Field:=3, Criteria1:=CarMeter(i), Operator:=xlAnd 'auto filters column 3 to the assigned meter value for each loop
Set toCopyRange = ws1rg.SpecialCells(xlCellTypeVisible) 'only copies visible cells from filtered content
End With
toCopyRange.Copy ws3.Cells(1, 1)
On Error Resume Next
ws3.Range("A1:C3000").EntireRow.SpecialCells(xlBlanks).EntireRow.Delete 'deletes blank rows
On Error GoTo Whoa
ws3lastrow = ws3.Cells(Rows.Count, 1).End(xlUp).Row
Getthelast:
For v = ws3lastrow - 1 To 2 Step -1
StartDate = ws3.Cells(v, 1)
EndDate = ws3.Cells(v + 1, 1)
EndDate = DateSerial(Year(EndDate), Month(EndDate), Day(EndDate))
StartDate = DateSerial(Year(StartDate), Month(StartDate), Day(StartDate))
'MsgBox (Month(EndDate) - Month(StartDate))
If (Month(EndDate) - Month(StartDate) > 1) Or (Month(EndDate) - Month(StartDate) < -1) Then
If Not (Month(EndDate) - Month(StartDate) = -11) Then
ws3.Cells(v + 1, 1).EntireRow.Insert
ws3.Cells(v + 1, 1) = DateAdd("m", 1, StartDate)
ws3.Cells(v + 1, 2) = "missing"
ws3.Cells(v + 1, 3) = CarMeter(i)
v = v + 2
End If
End If
' ws3lastrow = ws3.Cells(Rows.Count, 1).End(xlUp).Row
Next v
With ws3rg
.AutoFilter Field:=2, Criteria1:="missing", Operator:=xlAnd
Set toCopyFinal = ws3rg.SpecialCells(xlCellTypeVisible)
End With
On Error Resume Next
ws4lastrow = ws4.Cells(Rows.Count, 1).End(xlUp).Row
toCopyFinal.Copy ws4.Cells(ws4lastrow + 1, 1)
Next
Set ws4rg = ws4.Range("A:C")
With ws4rg 'only applies to ws1rg
.AutoFilter Field:=2, Criteria1:="missing", Operator:=xlAnd 'auto filters column 3 to the assigned meter value for each loop
End With
LetsContinue: 'runs protocol at end to turn on screen updating and calculations
Application.ScreenUpdating = True
Calculation = xlCalculationAutomatic
Exit Sub
Whoa: 'error protocol to display error message with description
MsgBox Err.Description
Resume LetsContinue
End Sub
Bookmarks