Run Time Error 91 "Object variable or With Block variable not set"

Sanjay Vernekar

New Member
Joined
May 28, 2020
Messages
3
Office Version
  1. 2016
Platform
  1. Windows
Hi all,

I am new to VB scripts . My requirement is to delete all the content of the table (Table structure should remain intact with headers) from all the worksheets in excel.
Each worksheets has multiple tables. Basically we are clearing all the table data so that it can freshly be entered.

I have written the code as below

Sub cleardata()

Dim tbl As ListObject
Dim sht As Worksheet

'Loop through each sheet and table in the workbook
For Each sht In ThisWorkbook.Worksheets

' Ignoring Contents and Cover Page sheet as its contains tables
If sht.Name <> "Contents" And sht.Name <> "Cover Page" Then
For Each tbl In sht.ListObjects

tbl.DataBodyRange.ClearContents

Next tbl
End If
Next sht
End Sub

This code worked in one workbook but not working in another as I am getting a run time error 91. Can you please guide me here.

Thanks in advance,
Sanjay
 

Excel Facts

Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
Probably a table with no body (headers created but no data added to it). Adding an error trap should correct that.
VBA Code:
Sub cleardata()
    Dim tbl As ListObject
    Dim sht As Worksheet
        'Loop through each sheet and table in the workbook
For Each sht In ThisWorkbook.Worksheets

        ' Ignoring Contents and Cover Page sheet as its contains tables
    If sht.Name <> "Contents" And sht.Name <> "Cover Page" Then
        For Each tbl In sht.ListObjects
            On Error Resume Next
            tbl.DataBodyRange.ClearContents
            On Error GoTo 0
        Next tbl
    End If
Next sht
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,583
Messages
6,120,383
Members
448,955
Latest member
BatCoder

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top