Skip to content

Instantly share code, notes, and snippets.

@HerbFargus
Last active May 1, 2017 17:47
Show Gist options
  • Save HerbFargus/110ea88317aaafb18fad7d50c887524d to your computer and use it in GitHub Desktop.
Save HerbFargus/110ea88317aaafb18fad7d50c887524d to your computer and use it in GitHub Desktop.
VBA (Excel): If the cell is blank, copy a value from another cell. Has options if it is blank or if its a null string (which apparently are different things)
' Excel VBA Macro: This compares two columns and if a field is empty, it will copy a value from a different field.
Sub Main()
With Application ' Optimise so deleting rows doesnt hang
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
' Set up prompt input boxes for user to choose the columns
Column1 = InputBox("Choose the column you want copied...")
If Column1 = "" Or DelimitedColumn1 Like "*[!A-Za-z]*" Then Exit Sub
Column2 = InputBox("Choose the column with empty cells...")
If Column2 = "" Or Column2 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
If IsEmpty(Range(Column2 & i).Value) Then Range(Column2 & i) = Range(Column1 & i) ' Check if Column 1 is blank, if so Copy the value from Column 2
If Range(Column2 & i) = vbNullString Then Range(Column2 & i) = Range(Column1 & i) ' Check if Column 1 is a null string (""), if so Copy the value from Column 2
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