• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Clear Empty Cells macro and merged cells error|VBA & Macros|Excel Forum|My Online Training Hub

You are here: Home / Clear Empty Cells macro and merged cells error|VBA & Macros|Excel Forum|My Online Training Hub
Avatar
sp_LogInOut Log In sp_Registration Register
sp_Search Search
Advanced Search|Last Search Results
Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search Search
sp_RankInfo
Lost password?
sp_CrumbsHome HomeExcel ForumVBA & MacrosClear Empty Cells macro and merged …
sp_PrintTopic sp_TopicIcon
Clear Empty Cells macro and merged cells error
Avatar
Blanka Blair
Member
Members
Level 0
Forum Posts: 53
Member Since:
October 17, 2015
sp_UserOfflineSmall Offline
1
November 17, 2018 - 7:06 am
sp_Permalink sp_Print

I use the following macro to clear empty cells all the time and I love it.

Recently I was using this macro on a file which had some merged cells. The macro threw the following error on the c.ClearContents line: "Run-time error '1004': We can't do that to a merged cell."

What needs to be altered in this macro so it also works for files with merged cells?

Thank you.

Blanka

 

Sub ClearEmptyCells1()
    ' Processes an entire worksheet
    ' Targets all cells containing constants and text
    ' If those cells contain only spaces, then the cells are cleared
   
    Dim TextCells As Range
    Dim c As Range
    Dim iCnt As Long
    Dim sTemp As String
   
    ' Set the range of cells to check: Only constants and text values
    Set TextCells = Cells.SpecialCells(xlCellTypeConstants, xlTextValues)
      
    For Each c In TextCells
        If Trim(c.Value) = "" Then
            ' Clear just the contents of the cell
                c.ClearContents
            iCnt = iCnt + 1
        End If
    Next c

    sTemp = "Cleared " & iCnt & " cell"
    If iCnt <> 1 Then sTemp = sTemp & "s"
    MsgBox sTemp
End Sub

sp_AnswersTopicSeeAnswer See Answer
Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
2
November 17, 2018 - 10:35 am
sp_Permalink sp_Print

Hi Blanka

Try this

Sub ClearEmptyCells1()
' Processes an entire worksheet
' Targets all cells containing constants and text
' If those cells contain only spaces, then the cells are cleared

Dim TextCells As Range
Dim c As Range
Dim iCnt As Long
Dim sTemp As String

' Set the range of cells to check: Only constants and text values
Set TextCells = Cells.SpecialCells(xlCellTypeConstants, xlTextValues)

For Each c In TextCells
If Trim(c.Value) = "" Then
' Clear just the contents of the cell
If c.MergeCells Then
c.MergeArea.ClearContents
Else
c.ClearContents
End If
iCnt = iCnt + 1
End If
Next c

sTemp = "Cleared " & iCnt & " cell"
If iCnt <> 1 Then sTemp = sTemp & "s"
MsgBox sTemp
End Sub

Sunny

sp_AnswersTopicAnswer
Answers Post
Avatar
Velouria
London or thereabouts
Moderator
Members


Trusted Members

Moderators
Level 4
Forum Posts: 648
Member Since:
November 1, 2018
sp_UserOfflineSmall Offline
3
November 19, 2018 - 8:20 pm
sp_Permalink sp_Print

You could use:

 

c.value = vbnullstring

 

which will work with merged cells too.

Avatar
Blanka Blair
Member
Members
Level 0
Forum Posts: 53
Member Since:
October 17, 2015
sp_UserOfflineSmall Offline
4
November 20, 2018 - 12:58 am
sp_Permalink sp_Print

Thank you Sunny so much. This works perfectly.

Velouria - thank you for your answer also. I wonder what the difference is between the two solutions. I added a MsgBox showing me the number of cells cleared and ran Sunny's code. According to the message box, 29 cells have been cleared. Immediately after that I ran the code again and message box shows 0 cells cleared, so this tells me that the first round of code did indeed clear all the empty cells.

I closed and reopened the file without saving and ran your code. Message box showed 29 cells cleared. I ran your code immediately after that and the message box showed 29 cells cleared again. Ran it again, and got the 29 cells again.

Thank you,

Blanka

Avatar
Velouria
London or thereabouts
Moderator
Members


Trusted Members

Moderators
Level 4
Forum Posts: 648
Member Since:
November 1, 2018
sp_UserOfflineSmall Offline
5
November 20, 2018 - 1:54 am
sp_Permalink sp_Print

I can't reproduce that. I get a number the first time and then 0 thereafter. What exact code did you use?

Avatar
Blanka Blair
Member
Members
Level 0
Forum Posts: 53
Member Since:
October 17, 2015
sp_UserOfflineSmall Offline
6
November 27, 2018 - 3:26 am
sp_Permalink sp_Print

Velouria,

I used the following:

Sub ClearEmptyCells1()
    
    Dim TextCells As Range
    Dim c As Range
    Dim iCnt As Long
    Dim sTemp As String
   
    ' Set the range of cells to check: Only constants and text values
    Set TextCells = Cells.SpecialCells(xlCellTypeConstants, xlTextValues)
   
   
   
    For Each c In TextCells
        If Trim(c.Value) = "" Then

               c.Value = vbNullString

            iCnt = iCnt + 1
        End If
    Next c
   
   
    sTemp = "Cleared " & iCnt & " cell"
    If iCnt <> 1 Then sTemp = sTemp & "s"
    MsgBox sTemp

End Sub

 

Did I do it incorrectly?

Thank you.

Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
7
November 27, 2018 - 10:44 am
sp_Permalink sp_Print

Hi Blanka

I too am unable to replicate your result.

I am getting the same result as Velouria. 1st time there is a number, 2nd time is 0.

Can't be sure of the reason. Possibly your data.

Are you able to post your file for us to have a look?

Sunny

Avatar
Blanka Blair
Member
Members
Level 0
Forum Posts: 53
Member Since:
October 17, 2015
sp_UserOfflineSmall Offline
8
November 28, 2018 - 1:26 am
sp_Permalink sp_Print

Hi Sunny,

Here is the file. I replaced only the actual data with fake values. The rest is untouched.

When I first run it with c.Value = vbNullString, I get 32 cleared cells, then in subsequent tries I keep getting 29 cleared cells.

At this point I'm very curious what it could be.

Thank you,

Blanka

Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
9
November 28, 2018 - 2:12 pm
sp_Permalink sp_Print sp_EditHistory

Hi Blanka

From your file there are actually 3 cells that has blank spaces in them: cells E34, B48, M48

Because of the merged cells, the macro gives 32 cells cleaned (1st time) and then 29 cells cleaned (subsequently)

The 3 cells (E34, B48, M48) are actually cleaned the 1st time while nothing got cleaned after that.

The comparison If Trim(c.Value) = "" is giving the wrong results for merged cells.

The 29 cells came from the merged cells. Somehow the SpecialCells keep on selecting them.

If you unmerged the cells, both ClearContents and vbNullString gives the correct result of 3 cells cleaned and later 0 cells cleaned if you ran it again.

I can't explain this behavior but to be on the safe side I suggest you use the codes that I suggested since it works.

My advice is to avoid merged cells as it causes lot of problem. In this case I believe it is unavoidable as the file is downloaded from somewhere else.

Sunny

Avatar
Velouria
London or thereabouts
Moderator
Members


Trusted Members

Moderators
Level 4
Forum Posts: 648
Member Since:
November 1, 2018
sp_UserOfflineSmall Offline
10
November 28, 2018 - 7:35 pm
sp_Permalink sp_Print

You can also fix it by not clearing cells that are actually empty (which is after all fairly pointless) by making a small change to the condition:

If Trim(c.Value) = "" And Not IsEmpty(c.Value) Then

Avatar
Blanka Blair
Member
Members
Level 0
Forum Posts: 53
Member Since:
October 17, 2015
sp_UserOfflineSmall Offline
11
November 29, 2018 - 12:47 am
sp_Permalink sp_Print

Sunny, Velouria, thank you both for your help.

Very kind of you to provide the explanations. You've been very helpful.

By the way, the files are from outside entities and we have no say in how they are generated so I'll have to live with the merged cells.

Thank you,

Blanka

Avatar
SunnyKow
Puchong, Malaysia

VIP
Members


Trusted Members
Level 8
Forum Posts: 1432
Member Since:
June 25, 2016
sp_UserOfflineSmall Offline
12
November 29, 2018 - 1:23 am
sp_Permalink sp_Print

Hi Blanka

You are welcome.

Let us know if you have anymore issues.

Sunny

sp_Feed
Go to top
Forum Timezone: Australia/Brisbane
Most Users Ever Online: 245
Currently Online:
Guest(s) 10
Currently Browsing this Page:
1 Guest(s)
Top Posters:
SunnyKow: 1432
Anders Sehlstedt: 873
Purfleet: 414
Frans Visser: 346
David_Ng: 306
lea cohen: 222
Jessica Stewart: 215
A.Maurizio: 202
Aye Mu: 201
jaryszek: 183
Newest Members:
Anthony van Riessen
Erlinda Eloriaga
Abisola Ogundele
MARTYN STERRY
Rahim Lakhani
Ngoc Qui Nguyen
Clement Mansfield
Rose .
Bindu Menon
Baruch Zemer
Forum Stats:
Groups: 3
Forums: 24
Topics: 6352
Posts: 27779

 

Member Stats:
Guest Posters: 49
Members: 32319
Moderators: 3
Admins: 4
Administrators: Mynda Treacy, Philip Treacy, Catalin Bombea, FT
Moderators: MOTH Support, Velouria, Riny van Eekelen
© Simple:Press —sp_Information

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.