Last active
March 30, 2020 15:35
-
-
Save sheepeeh/0eb256331d4a511e658589a39d5452b7 to your computer and use it in GitHub Desktop.
Word VBA: Copy text from previous column if current column is empty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' Usage: Select/place your cursor in the cell you want to copy text TO, | |
' then run the macro. It will loop through all rows, so only select | |
' one cell. | |
' The first macro will copy text into blank cells for the currently | |
' selected table. | |
' | |
' The second will do this for the selected columns in all tables | |
' in the document. | |
' | |
' Note: does not account for cells that might have invisible content | |
' like spaces or tabs. | |
Sub copyColumnTextIfBlank() | |
' For the currently selected table and column, copies the text of | |
' previous column into current column if the current column cell | |
' is blank. | |
Dim iTable As Integer | |
Dim myTable As Word.Table | |
Dim currentCol As Integer | |
Dim prevCol As Integer | |
' Check if Selection IS in a table | |
' if not, exit Sub after message | |
If Selection.Information(wdWithInTable) = False Then | |
MsgBox "Selection is not in a table. Exiting macro." | |
Else | |
iTable = ActiveDocument.Range(0, Selection.Paragraphs(1).Range.End).Tables.Count | |
Set myTable = ActiveDocument.Tables(iTable) | |
currentCol = Selection.Cells(1).ColumnIndex | |
prevCol = currentCol - 1 | |
For Each r In myTable.Rows | |
If myTable.Cell(r.Index, currentCol).Range.Text = Chr(13) & Chr(7) Then | |
myTable.Cell(r.Index, currentCol).Range.InsertAfter Text:=myTable.Cell(r.Index, prevCol).Range.Text | |
End If | |
Next | |
End If | |
End Sub | |
Sub CopyIfBlankAllTables() | |
Dim currentCol As Integer | |
Dim prevCol As Integer | |
' Check if Selection IS in a table | |
' if not, exit Sub after message | |
If Selection.Information(wdWithInTable) = False Then | |
MsgBox "Selection is not in a table. Exiting macro." | |
Else | |
currentCol = Selection.Cells(1).ColumnIndex | |
prevCol = currentCol - 1 | |
For Each tbl In ActiveDocument.Tables | |
For Each r In tbl.Rows | |
If tbl.Cell(r.Index, currentCol).Range.Text = Chr(13) & Chr(7) Then | |
tbl.Cell(r.Index, currentCol).Range.InsertAfter Text:=tbl.Cell(r.Index, prevCol).Range.Text | |
End If | |
Next | |
Next | |
End If | |
End Sub | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment