You are here:

Excel/loop through nonbalnk cells and copy


Tom: Thanks as always, I want a macro to search cells B3:Z100 for each sheet in the workbook and find each non blank cell, if not blank copy the data (as text not a formula)then paste it to another sheet named "Stuff" in only column A successively down the rows.

Example , Three sheets in workbook named "Data" "Header", and "Stringer"

Searching "Data" it finds something in B3 and D4 so it pastes it into "Stuff at A1 and A2
continuing it finds something in"Header" at J32 and X33 so it pastes it into "Stuff" at A3 and A4
continuing it finds formulas in "Stringer" in Z90, Z92 and Z100 so it pastes the values (not formulas) in "Stuff" at A5, A6 and A7.

Hopefully it is clear.



See if this does what you want.

Sub copydata()
Dim sh As Worksheet, rw As Long
Dim v As Variant, v1 As Variant
Dim sh1 As Worksheet, ii As Long
Dim i As Long, j As Long
Set sh1 = Worksheets("Stuff")
rw = 1
v = Array("Data", "Header", "Stringer")
For ii = LBound(v) To UBound(v)
 Set sh = Worksheets(v(ii))
 v1 = sh.UsedRange.Value
 For i = 1 To UBound(v1, 1)
  For j = 1 To UBound(v1, 2)
   If Not IsError(v1(i, j)) Then
    If Len(Trim(v1(i, j))) > 0 Then
       sh1.Cells(rw, "A").Value = v1(i, j)
       rw = rw + 1
    End If
   End If
  Next j
 Next i
Next ii
End Sub

Tom Ogilvy  
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Tom Ogilvy


Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]


Extensive experience.

Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2016 All rights reserved.