Search code examples
vbaexcelexcel-2013

delete blank rows on an excel worksheet, in a different excel workbook, using vba


I have 2 work books. Book_A and Book_B.

I want to delete blank rows in Book_A worksheet1, from Book_B worksheet1.

I have written a code using VBA to delete blank rows.

Sub RemoveEmptyRows()

' this macro will remove all rows that contain no data

Dim i             As Long
Dim LastRow      As Long

LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Application.ScreenUpdating = False

For i = LastRow To 1 Step -1

  If WorksheetFunction.CountA(ActiveSheet.Rows(i)) = 0 Then
   ActiveSheet.Rows(i).EntireRow.Delete

End If
Next i

Application.ScreenUpdating = True
End Sub

This code works and enables me to delete blank rows of a worksheet.

Say i have rows in Book_A, worksheet1,using the vba editor,

i insert a module for VBA project Book_A and type the coding,

and run the macro,

the blank rows in Book_A, worksheet1 get deleted.

............................................................................

**But: This code will not enable me to delete blank rows in Book_A worksheet1, from Book_B worksheet1.

I want to delete blank rows in Book_A worksheet1, from Book_B worksheet1.

How can this be done? How do i edit my coding? **


Solution

  • This is very easy to do..

    Sub RemoveEmptyRows()
    
    ' this macro will remove all rows that contain no data
    
    Dim file_name as String
    Dim sheet_name as String
    
       file_name = "c:\my_folder\my_wb_file.xlsx"  'Change to whatever file you want
       sheet_name = "Sheet1"   'Change to whatever sheet you want
    
    Dim i             As Long
    Dim LastRow      As Long
    
    Dim wb As New Workbook
    
    Set wb = Application.Workbooks.Open(file_name)
    
    wb.Sheets(sheet_name).Activate
    
    
    
    
    LastRow = wb.ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
    Application.ScreenUpdating = False
    
    For i = LastRow To 1 Step -1
    
      If WorksheetFunction.CountA(wb.ActiveSheet.Rows(i)) = 0 Then
       wb.ActiveSheet.Rows(i).EntireRow.Delete
    
    End If
    Next i
    
    Application.ScreenUpdating = True
    End Sub