Skip to content

Instantly share code, notes, and snippets.

@HerbFargus
Last active May 1, 2017 15:57
Show Gist options
  • Save HerbFargus/4eb0c55ac03acaf21a63408635597d49 to your computer and use it in GitHub Desktop.
Save HerbFargus/4eb0c55ac03acaf21a63408635597d49 to your computer and use it in GitHub Desktop.
VBA (Excel): Filling in the gaps between hundredth mileposts
' Excel VBA Macro: This takes a list of endpoints and automatically generates rows for each hundredth point between the two columns: beginning milepost and the ending milepost
Sub Main()
With Application ' Optimise so inserting rows doesnt hang
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
' Set up prompt input boxes for user to choose the columns
Column1 = InputBox("Choose the beginning milepoint column...")
If Column1 = "" Or DelimitedColumn1 Like "*[!A-Za-z]*" Then Exit Sub
Column2 = InputBox("Choose the ending milepoint column...")
If Column2 = "" Or Column2 Like "*[!A-Za-z]*" Then Exit Sub
Column3 = InputBox("Choose an empty column to place results...")
If Column3 = "" Or Column3 Like "*[!A-Za-z]*" Then Exit Sub
lastRow = Range("A" & Rows.Count).End(xlUp).Row ' finding last row used
For i = lastRow To 1 Step -1 ' iterating from last row to 1st
difference = Round(Range(Column1 & i), 2) - Round(Range(Column2 & i), 2) ' calculating the difference
difference = Round(difference, 2) ' round because float comparisons are inconsistent
If difference < 0 Then ' if difference meets your criteria
For j = difference To 0 Step 0.01 ' how many rows to insert
j = Round(j, 2) ' round because float comparisons are inconsistent
Rows(i).Copy ' copy the origin
Range("A" & i + 1).Insert Shift:=xlDown ' insert the copied row
Range(Column3 & i + 1) = Range(Column1 & i + 1) + Abs(j) ' increment milepost
'Debug.Print j
Next
If IsEmpty(Range(Column3 & i).Value) Then Rows(i).EntireRow.Delete ' remove original field
If Range(Column3 & i) = vbNullString Then Rows(i).EntireRow.Delete ' remove original field
ElseIf difference > 0 Then ' if difference meets your criteria
For j = 0 To difference Step 0.01 ' how many rows to insert
j = Round(j, 2) ' round because float comparisons are inconsistent
Rows(i).Copy ' copy the origin
Range("A" & i + 1).Insert Shift:=xlDown ' insert the copied row
Range(Column3 & i + 1) = Range(Column1 & i + 1) - Abs(j) ' increment milepost
'Debug.Print j
Next
If IsEmpty(Range(Column3 & i).Value) Then Rows(i).EntireRow.Delete ' Check if Cell is Blank, if so delete entire row
If Range(Column3 & i) = vbNullString Then Rows(i).EntireRow.Delete ' Check if Cell is a null string (""), if so delete entire row
End If
Next
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
.CutCopyMode = False
End With
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment