Modify macro to ignore blanks cells in changing columns to rows - advanced

Maggie Barr

Board Regular
Joined
Jan 28, 2014
Messages
188
Hello there,
I found an amazing macro on this forum by Hiker95 that works perfectly for me except that I would like for it to ignore blank cells within the dataset. I am using a PC with Excel 2010. When I run the macro it gives me what I want, but it also creates rows for cells within the spreadsheet that are blanks, and I would like for it to not create rows for the blank cells. In column A I have the current scientific Latin name of a plant, and in the subsequent columns (B-Q) I have Latin synonymy. I would like Column A to get repeated and Have columns B-Q get put in Column B with the heading of those columns in Column C (Please see sheet 2 of the Box Net file below for example). The Macro gave me Column A repeated to match the synonymy in Column B (from all the other columns), but there are many blanks.
So Sorry for not being able to display the data, I am new to all of this, and I have tried to post examples/screanshots of my data using MrExceHtml, but when I paste it, only a large amount of what look like garble is visible (hopefully I can figure this one out soon).
I have uploaded my file to Box Net: https://app.box.com/s/pdcvamsr9dtm8atsmz6d
In sheet one is the raw data, and in sheet two is the data after the macro was run.
In case the macro doesn't come through as visible in developer through Box Net the macro I ran is below:
Thank you all so much for your time and help, and sorry for my inabilities to post screenshots yet.
Best Wishes,
Maggie

Code:
Sub ReorgData()
'   hiker95, 08/04/2014, ME796335
    Dim w1 As Worksheet, w2 As Worksheet
    Dim a As Variant, o As Variant
    Dim i As Long, j As Long
    Dim lr As Long, lc As Long, c As Long, n As Long
    Application.ScreenUpdating = False
    Set w1 = Sheets("Sheet1")
    Set w2 = Sheets("Sheet2")
    With w1
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        lc = .Cells(1, Columns.Count).End(xlToLeft).Column
        a = .Range(.Cells(1, 1), .Cells(lr, lc))
        n = ((lr - 1) * (lc - 1)) + 1
        ReDim o(1 To n, 1 To 3)
    End With
    j = j + 1
    o(j, 1) = "Name"
    o(j, 2) = "value"
    o(j, 3) = "Yr"
    For i = 2 To lr
        For c = 2 To lc
            j = j + 1
            o(j, 1) = a(i, 1)
            o(j, 2) = a(i, c)
            o(j, 3) = Right(a(1, c), Len(a(1, c)) - 2)
        Next c
    Next i
    With w2
        .UsedRange.ClearContents
        .Cells(1, 1).Resize(n, 3).Value = o
        .Columns(1).Resize(, 3).AutoFit
        .Activate
    End With
    Application.ScreenUpdating = True
End Sub
 
Last edited by a moderator:

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
Hello There,
I found a macro (on this forum) to run that would delete rows based on a referenced blank cell within it:
Sub deleteBlankRows()
On Error Resume Next
Columns("B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
I then did a COUNTA to total the columns with references in the raw data and summed those to make sure the macro hadn't deleted anything it shouldn't (I am the nervous sort).

I would still like to know if the original macro I ran could be modified as I could use it in the future, so if anyone can tackle this it would be greatly appreciated.

Thank you Hiker95 for helping, and for the detail you gave associated with the macro you provided in the post "Copying columns to rows - advanced". It is great to see it all spelled out so we can understand and learn.
I have to say that I am so deeply appreciative of the kind and supportive folks on this forum, and it is all so exciting to learn from you all.
Best Wishes,
Maggie
 
Upvote 0
Maggie Barr,

Thanks for the Private Message, and, for following my instructions to start a NEW thread.

When I launch your posted link to BOX, BOX is asking for an ID, and, Password?????


You can upload your workbook to Box Net,

sensitive data changed

mark the workbook for sharing

and provide us with a link to your workbook.
 
Upvote 0
Hello Again Hiker,
I did click share, not sure what went wrong. I accessed it again, clicked share, and made sure it said anyone with the link again, perhaps it will work now. So very sorry for the inconvenience. I have this link now, but it is the same as the one given, I do not know if there is a way to save the settings or not, because as I go back into Box Net it doesn't show my share setting the next time:

https://app.box.com/s/pdcvamsr9dtm8atsmz6d

It appears that when I open this up it illustrates a the first sheet not sheet two, and I do not know if it will let someone download the file or not. This is all new to me, so I am sorry. I did research the print scream, and I think my error is in having a 64 bit windows and 32 bit Excel, or at least I am finding posts on this forum related to complications associated with these operating systems and that is what I have.

I do not see an option here to attach files to these emails, or, if you requested, I could.

Thanks for staying with me on this issue and helping me learn more about Excel and how this forum works.
Maggie
 
Upvote 0
Hiker,
I did just go to my post and click on the link, and it opened, so perhaps we can get somewhere now.
Thank,
Maggie
 
Upvote 0
Maggie Barr,

Thanks for the workbook.

I will not be able to display screenshots because of the size of your raw data worksheet Sheet1, and, because of the size of your results worksheet Sheet2.


Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

1. Copy the below code
2. Open your NEW workbook
3. Press the keys ALT + F11 to open the Visual Basic Editor
4. Press the keys ALT + I to activate the Insert menu
5. Press M to insert a Standard Module
6. Where the cursor is flashing, paste the code
7. Press the keys ALT + Q to exit the Editor, and return to Excel
8. To run the macro from Excel press ALT + F8 to display the Run Macro Dialog. Double Click the macro's name to Run it.

Code:
Sub ReorgData()
' hiker95, 09/01/2014, ME802529
Dim w1 As Worksheet, w2 As Worksheet
Dim a As Variant, o As Variant
Dim i As Long, j As Long
Dim lr As Long, lc As Long, c As Long
Application.ScreenUpdating = False
Set w1 = Sheets("Sheet1")
Set w2 = Sheets("Sheet2")
With w1
  lr = .Cells(Rows.Count, 1).End(xlUp).Row
  lc = .Cells(1, Columns.Count).End(xlToLeft).Column
  a = .Range(.Cells(1, 1), .Cells(lr, lc))
  ReDim o(1 To (lr * lc) + 1, 1 To 3)
End With
j = j + 1
o(j, 1) = "Current Name"
o(j, 2) = "Synonym"
o(j, 3) = "Synonym #"
For i = 2 To lr
  For c = 2 To lc Step 1
    j = j + 1
    o(j, 1) = a(i, 1)
    o(j, 2) = a(i, c)
    o(j, 3) = "nonymy " & c - 1 & " WITHOUT authors"
  Next c
Next i
With w2
  .UsedRange.ClearContents
  .Cells(1, 1).Resize((lr * lc) + 1, 3).Value = o
  .Columns.AutoFit
  .Activate
End With
Application.ScreenUpdating = True
End Sub

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm

Then run the ReorgData macro.
 
Upvote 0
Maggie Barr,

When I run the macro it gives me what I want, but it also creates rows for cells within the spreadsheet that are blanks, and I would like for it to not create rows for the blank cells.

I think that I missed the above.

I assumed that the correct output was what was displayed on Sheet2 or your workbook on BOX

Be back in a little while.
 
Upvote 0
Maggie Barr,

If my last reply was correct, and, if I understand your new requirements, then:

Sample raw data worksheet Sheet1 (not all rows, and, columns are shown for brevity):


Excel 2007
ABCDQ
1Scientific Name and var.No Authority (Red highlight are species added because of apparent error in not being in FL. O. ME.)Synonymy 1 WITHOUT authorsSynonymy 2 WITHOUT authorsSynonymy 3 WITHOUT authorsSynonymy 16 WITHOUT authors
2Abies balsameaAbies balsamea var. phanerolepisPinus balsamea
3Abies concolor
4Abutilon theophrastiAbutilon abutilon
5Acalypha rhomboideaAcalypha virginica var. rhomboidea
6Acalypha virginicaAcalypha digyneia
7Acer freemaniiAcer rubrum A. saccharinum
8Acer ginnala
9Acer negundo var. negundoNegundo aceroidesNegundo negundo
10Acer negundo var. violaceumAcer violaceumNegundo aceroides ssp. violaceumNegundo aceroides var. violaceum
Sheet1


After the new macro (using two arrays in memory) in worksheet Sheet2 (not all rows, and, columns are shown for brevity):


Excel 2007
ABC
1Current NameSynonymSynonym #
2Abies balsameaAbies balsamea var. phanerolepisnonymy 1 WITHOUT authors
3Abies balsameaPinus balsameanonymy 2 WITHOUT authors
4Abutilon theophrastiAbutilon abutilonnonymy 1 WITHOUT authors
5Acalypha rhomboideaAcalypha virginica var. rhomboideanonymy 1 WITHOUT authors
6Acalypha virginicaAcalypha digyneianonymy 1 WITHOUT authors
7Acer freemaniiAcer rubrum A. saccharinumnonymy 1 WITHOUT authors
8Acer negundo var. negundoNegundo aceroidesnonymy 1 WITHOUT authors
9Acer negundo var. negundoNegundo negundononymy 2 WITHOUT authors
10Acer negundo var. violaceumAcer violaceumnonymy 1 WITHOUT authors
11Acer negundo var. violaceumNegundo aceroides ssp. violaceumnonymy 2 WITHOUT authors
12Acer negundo var. violaceumNegundo aceroides var. violaceumnonymy 3 WITHOUT authors
Sheet2


Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

Code:
Sub ReorgData_NoBlanks()
' hiker95, 09/02/2014, ME802529
Dim w1 As Worksheet, w2 As Worksheet
Dim a As Variant, o As Variant
Dim i As Long, j As Long
Dim lr As Long, lc As Long, c As Long, n As Long
Application.ScreenUpdating = False
Set w1 = Sheets("Sheet1")
Set w2 = Sheets("Sheet2")
With w1
  lr = .Cells(Rows.Count, 1).End(xlUp).Row
  lc = .Cells(1, Columns.Count).End(xlToLeft).Column
  a = .Range(.Cells(1, 1), .Cells(lr, lc))
  n = Application.CountA(.Range(.Cells(2, 2), .Cells(lr, lc)))
  ReDim o(1 To n + 1, 1 To 3)
End With
j = j + 1
o(j, 1) = "Current Name"
o(j, 2) = "Synonym"
o(j, 3) = "Synonym #"
For i = 2 To lr
  For c = 2 To lc Step 1
    If a(i, c) <> "" Then
      j = j + 1
      o(j, 1) = a(i, 1)
      o(j, 2) = a(i, c)
      o(j, 3) = "nonymy " & c - 1 & " WITHOUT authors"
    End If
  Next c
Next i
With w2
  .UsedRange.ClearContents
  .Cells(1, 1).Resize(n + 1, 3).Value = o
  .Columns.AutoFit
  .Activate
End With
Application.ScreenUpdating = True
End Sub

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm

Then run the ReorgData_NoBlanks macro.
 
Upvote 0
Hiker,
Thank you so much for this. It worked perfectly! I will now spend some time reading through the macro to better understand the parts of it in detail. I always try to ask people if there are any particular reference materials they would recommend for better interpreting and learning what they have taught me, so if you know of any and could recommend them it would be greatly appreciated. I have started to use and rely on macros a lot in my work now and I have little to no training in writing VBA, so it would be great to know of good materials to help guide me through the learning process.
Thanks again for everything.
Best Wishes,
Maggie
 
Upvote 0
Maggie Barr,

Thanks for the feedback.

You are very welcome. Glad I could help.

And, come back anytime.



will now spend some time reading through the macro to better understand the parts of it in detail. I always try to ask people if there are any particular reference materials they would recommend for better interpreting and learning what they have taught me

If you would like, I can add comments to the macro code to explain what is happening?


I have started to use and rely on macros a lot in my work now and I have little to no training in writing VBA, so it would be great to know of good materials to help guide me through the learning process.

See if something in my most up to date list will help you:

Training / Books / Sites as of 8/30/2014

What Is VBA?
VBA is an acronym for Visual Basic for Applications. VBA should not be confused with VB, which is standard Visual Basic. Visual Basic for Applications is a programming feature designed by Microsoft for use with their Microsoft Office

MrExcel's Products: Books, CDs, Podcasts Discuss topics related to Holy Macro! Products: Learn Excel from MrExcel, VBA and Macros for Microsoft Excel,Holy Macro! It's 2500 VBA Examples CD, Guerilla Data Analysis Using Microsoft Excel and Excel Knowledge Base CD and the MrExcel Podcasts.
MrExcel's Products: Books, CDs, Podcasts

There are over 1800 Excel videos/tutorials here:
ExcelIsFun - YouTube

Getting Started with VBA.
DataPig Technologies

If you are serious about learning VBA try
http://www.add-ins.com/vbhelp.htm

Excel Tutorials and Tips - VBA - macros - training
MrExcel.com | Excel Resources | Excel Seminars | Excel Products

MrExcel's Excel Tutorial Listing
MrExcel.com | Excel Resources | Excel Seminars | Excel Products

Free VBA Course
Free VBA Course

Excel 2007 VBA materials to learn here:
VBA for Excel 2007 tutorial-VBA programming?

The macro recorder actually is your friend but look here:
Beyond Excel's recorder

Here's a good primer on the scope of variables.
Understanding Scope

Using Variables in Excel VBA Macro Code
Excel VBA Variables. Using Variables in Excel VBA Macro Code

See David McRitchie's site if you just started with VBA
Getting Started with Macros and User Defined Functions

What is a VBA Module and How is a VBA Module Used?
What Is A VBA Module and how is a VBA Module Used?

Events And Event Procedures In VBA
Events In Excel VBA

Here is a good introductory tutorial using a VBA Class:
Classes In VBA

There's a chapter on classes in VBA Developer's Handbook which is also good.
VBA Developer's Handbook, 2nd Edition: Ken Getz, Mike Gilbert: 0025211229781: Amazon.com: Books

Ron's Excel Tips
Excel for Windows Tips

Ron de Bruin's Mail from Excel and make/mail PDF files (Windows)
Mail from Excel and make/mail PDF files (Windows)

How do I create and use a PERSONAL file for my VBA code
How do I create and use a PERSONAL file for my VBA code

Anthony's Excel VBA Page - Excel Application - Excel Consultant - Excel Consulting (see 3 tutorials in Excel VBA Basic Tutorial Series)

BET: Microsoft Excel Visual Basic

Debugging VBA
Debug Excel VBA Macro Code
TechBookReport - Debugging Excel VBA Code

Start at the beginning...

Creating An XLA Add-In For Excel, Writing User Defined Functions In VBA
Creating An XLA Add In

Build an Excel Add-In
VBA Tips: Build an Excel Add-In

Creating custom functions
Creating custom functions - Excel

Writing Your First VBA Function in Excel
http://www.exceltip.com/st/Writing_Your_First_VBA_Function_in_Excel/631.html

VBA for Excel (Macros)
Excel Macros (VBA) Tutorial

Excel Macros Tutorial
Excel Macros (VBA) Tutorial

Excel Macros & Programming
EXCEL Macros Tutorial

VBA Lesson 11: VBA Code General Tips and General Vocabulary
VBA for Excel macros language

Excel VBA -- Adding Code to a Workbook
http://www.contextures.com/xlvba01.html

Beyond Excel's recorder

Helpful as a simple concise reference for the basics, and, using the macro recorder is endlessly powerful.
MS Excel: Cells

Learn to debug:
Debugging VBA

How To: Assign a Macro to a Button or Shape
How To: Assign a Macro to a Button or Shape - Peltier Tech Blog

User Form Creation
http://www.contextures.com/xlUserForm01.html

Build a UserForm for Excel
http://www.fontstuff.com/ebooks/free/fsuserforms.pdf

When To Use a UserForm & What to Use a UserForm For
When to use Userform & What To Use Them For. Excel Training VBA 2 lesson 2

Excel Tutorials / Video Tutorials - Functions
http://www.contextures.com/xlFunctions02.html

How to insert Buttons, radio buttons and check boxes in Excel
How to insert Buttons, radio buttons and check boxes in Excel - Bing Videos

INDEX MATCH - Excel Index Function and Excel Match Function
http://www.contextures.com/xlFunctions03.html

Multi or two way vlook up and index match tutorial
Get Digital Help - Excel formulas, array formulas, vba, charts, pivot tables, templates and much more.

Excel Data Validation
http://www.contextures.com/xlDataVal08.html#Larger
http://www.contextures.com/excel-data-validation-add.html

Excel -- Data Validation -- Create Dependent Lists
http://www.contextures.com/xlDataVal02.html

Your Quick Reference to Microsoft Excel Solutions
XL-CENTRAL.COM : For your Microsoft Excel Solutions

New! Excel Recorded Webinars
DataPig Technologies

Fuzzy Matching - new version plus explanation

Programming The VBA Editor - Created by Chip Pearson at Pearson Software Consulting LLC
This page describes how to write code that modifies or reads other VBA code.
Programming In The VBA Editor

VBA and Macros for Microsoft Excel, by Bill Jelen "Mr.Excel" and Tracy Syrstad

Excel Hacks 100 Industrial-Strength Tips & Tools, by David & Traina Hawley

VBA and Macros for Microsoft Excel 2007, by Bill Jelen "Mr.Excel" and Tracy Syrstad

John Walkenbach's power programming with Excel books.

Excel 2010 Power Programming with VBA, Mr. Spreadsheet's Bookshelf

by Stephen/ Bovey, Rob/ Green, John Bullen (Paperback - Feb 11, 2005)
Professional Excel Development

by Rob Bovey, Stephen Bullen, John Green, and Robert Rosenberg (Paperback - Sep 26, 2001)
Excel 2002 VBA: Programmers Reference

Professional Excel Development by Rob Bovey, Dennis Wallentin, Stephen Bullen, & John Green

DonkeyOte: My Recommended Reading, Volatility
Volatile Excel Functions -Decision Models

A list of Reference Books
AJP Excel Information

Sumproduct
http://www.xldynamic.com/source/xld.SUMPRODUCT.html

Arrays
VBA Array Basics
VBA Arrays
Excel: Introduction to Array Formulas - Xtreme Visual Basic Talk
Excel VBA Chpter 21: Array in Excel VBA

Array Dimensions in Visual Basic - Working with Dimensions (code and graphics)
Array Dimensions in Visual Basic

Visual Basic Array Tutorial written by Adam Wehmann
Visual Basic Arrays Tutorial

Shortcut Keys in Excel 2000 through 2007

Pivot Intro
Using Pivot Tables and Pivot Charts in Microsoft Excel
Office 2010 Class #36: Excel PivotTables Pivot Tables 15 examples (Data Analysis) - YouTube
http://www.youtube.com/watch?v=qMGILHiLqr0
Getting Started with Pivot Tables
http://www.contextures.com/xlPivot01.html#Start
Overview of PivotTable and PivotChart reports
Overview of PivotTable and PivotChart reports - Excel
Build a Pivot Table in Excel VBA
Excel VBA - Build A Pivot Table In Excel VBA Tutorials

Conditional Formatting
Use a formula to apply conditional formatting - Excel

Email from XL - VBA
Mail from Excel example pages

Outlook VBA
Writing VBA code for Microsoft Outlook

Excel Function Dictionary by Peter Noneley
http://www.xlfdic.com/
www.xlfdic.com Excel Function Dictionary 150 example functions and formula.

Function Translations
Excel 2007 function name translations - Dictionary Chart Front Page

Dynamic Named Ranges
http://www.contextures.com/xlNames01.html

How to create Excel Dashboards
http://www.contextures.com/excel-dashboards.html
Excel Dashboards - Templates, Tutorials, Downloads and Examples | Chandoo.org - Learn Microsoft Excel Online
Excel Dashboards - Templates, Tutorials, Downloads and Examples | Chandoo.org - Learn Microsoft Excel Online
Free Microsoft Excel Dashboard Widgets to Download
Gauge

Excel Dashboard / Scorecard Ebook
Excel Dashboards and Scorecards Ebook | How to Create Dashboards in Excel

Mike Alexander from Data Pig Technologies
http://www.amazon.com/Excel-2007-Da...=sr_1_1?s=books&ie=UTF8&qid=1305564958&sr=1-1

Templates
CPearson.com Topic Index
http://www.contextures.com/excel-template-golf-scores.html
Free Microsoft Excel Template Links & Search Engine

Microsoft Excel Cascading Listboxes Tutorial
Microsoft Excel Cascading Listboxes Tutorial - YouTube

Date & Time stamping:
McGimpsey & Associates : Excel : Time and date stamps

Get Formula / Formats thru custom functions:
Show FORMULA or FORMAT of another cell

A nice informative MS article "Improving Performance in Excel 2007"
Improving Performance in Excel 2007

Progress Meters
Progress meters
xcelfiles.com

How to convert text to numbers in Excel
How to convert text to numbers in Excel

How to parse data from the web - Brett Fret has a video in YouTube
Excel VBA - Easily parse XML data from a file or website using XML Maps - YouTube

Excel VBA MAC shortcuts
http://www.mrexcel.com/forum/excel-questions/465614-mac-shortcuts-excel.html

Macintosh Keyboard Shortcuts to use in Microsoft Excel
Excel keyboard shortcuts - mac excel

Excel shortcut and function keys - Excel

And, as your skills increase, try answering threads on sites like:
MrExcel.com | Excel Resources | Excel Seminars | Excel Products
Excel Help Forum
Excel Templates | Excel Add-ins and Excel Help with formulas and VBA Macros
Expert Microsoft Help, with all of the Microsoft Applications from Excel programming, Access training to our free Microsoft VBA Forums
Excel, Access, PowerPoint and Word VBA Macro Automation Help

If you are willing to spend money for the training, then something here should work for you...
http://www.amazon.com/s/?ie=UTF8&ke...vpone=&hvptwo=&hvqmt=b&ref=pd_sl_5givffg47i_b

Advanced Excel Training - Online Excel Course
Excel Training: The Top Advanced Excel Course Online - Udemy

Excel VBA Programmer Interview - Excel Test for interview
Excel VBA Programmer Interview
 
Upvote 0

Forum statistics

Threads
1,223,234
Messages
6,170,891
Members
452,366
Latest member
TePunaBloke

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