SpecialCells(12).Value stops after first hidden row - excel

I'm currently trying to copy a filtered column to an array to populate a ComboBox in a Powerpoint presentation.
The line of code I'm using to do this is:
ar = tbl.ListColumns(ColNumber).Range.SpecialCells(12).Value
Where "ar" is the destination array, "tbl" is the source table and "ColNumber" is the number of column I'm trying to copy.
The filtered column I'm trying to copy has around 180 records but I noticed the destination array has 6 values since it selected only until the first "hidden" row in the range, and skipped every other visible row after that.
Is there a way to get the value of every visible row and not just the first ones?

You are facing that issue because of Non Contigous range. You cannot use the method Array = Range.Value for Non Contigous range. There are two ways you can follow to achieve what you want.
WAY 1 Identify the Range, Loop through the cells and populate the array. Suitable for your case as you are dealing with single column.
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim tbl As ListObject
Dim ar As Variant
Dim i As Long, n As Long, ColNumber As Long
Dim aCell As Range, rng As Range
'~~> Change this to the relevant sheet
Set ws = Sheet1
'~~> Change this to the relevant table
Set tbl = ws.ListObjects("Table1")
ws.AutoFilterMode = False
'~~> Change to relevant column number
ColNumber = 1
'~~> Autofilter as required
tbl.Range.AutoFilter Field:=ColNumber, Criteria1:="Blah1"
'~~> Set your range
Set rng = tbl.ListColumns(ColNumber).Range.SpecialCells(12)
'~~> Get the count of cells in that range
n = rng.Cells.Count
'~~> Resize the array to hold the data
ReDim ar(1 To n)
n = 1
'~~> Store the values from that range into the array
For Each aCell In rng.Cells
ar(n) = aCell.Value
n = n + 1
Next aCell
For i = LBound(ar) To UBound(ar)
Debug.Print ar(i)
Next i
End Sub
WAY 2 Identify the Range, loop thorough the Area and then loop through the cells in that Area and then populate the array. Very similar to the above code.
In Action

Related

Loop Visible Rows after filter & Copy to another Sheet base on Condition

I wanted to copy all visible rows from sheet1 table1 to sheet2 table2 after filter if Column B is empty. The code I have below only copy the last data to the other sheet and it will copy to the rest of the table.
Sub Send()
Dim i As Integer, j As Integer, k As Integer
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim visRng As Range ' Creating a range variable to store our table, excluding any rows that are filtered out.
Set wsCopy = Application.ThisWorkbook.Worksheets("Sheet1")
Set wsDest1 = Application.ThisWorkbook.Worksheets("Sheet2")
MsgBox "Sending Form...."
Set visRng = Range("Table1").SpecialCells(xlCellTypeVisible) 'Check all visible Rows in Table1
Dim r As Range
For Each r In visRng.Rows ' Loop through each row in our visible range ...
'MsgBox (r.Row) ' ... and retrieve the "absolute" row number.
If wsCopy.Cells(r.Row, 2).Value = "" Then
wsCopy.Range("A" & r.Row).Copy
wsDest1.Range("Table2").Columns(1).PasteSpecial
End If
Next
End Sub
here is sample filter in Sheet1 Table1
here is the result of my code in Sheet2 Table2
Expected Result: Sheet2 Table2
This should work:
Sub Send()
Dim i As Integer, j As Integer, k As Integer
Dim wsCopy As Worksheet
'IN THE CODE wsDest WAS CALLED wsDest1. I CHANGED THE REFERENCES IN THE CODE. I'D SUGGET YOU TO USE Option Explicit.
Dim wsDest As Worksheet
Dim visRng As Range ' Creating a range variable to store our table, excluding any rows that are filtered out.
'ADDED A NEW VARIABLE
Dim DblRow As Double
Set wsCopy = Application.ThisWorkbook.Worksheets("Sheet1")
Set wsDest = Application.ThisWorkbook.Worksheets("Sheet2")
MsgBox "Sending Form...."
'CHANGED visRng TO TARGET ONLY THE FIRST COLUMN OF Table1. NO NEED TO INCLUDE THE REST OF THE TABLE; IT WOULD ONLY MAKE OUR EXECUTION LONGER
Set visRng = Range("Table1").Columns(1).SpecialCells(xlCellTypeVisible) 'Check all visible Rows in Table1
'YOU SHOULD PUT THIS DECLARATION AT THE BEGINNING. ALSO I'D SUGGEST NOT TO USE A SINGLE LETTER VARIABLE. wsDest IS A GOOD NAME FOR A VARIABLE.
Dim r As Range
'SETTING THE VARIABLE.
DblRow = 1
For Each r In visRng.Rows ' Loop through each row in our visible range ...
'MsgBox (r.Row) ' ... and retrieve the "absolute" row number.
If wsCopy.Cells(r.Row, 2).Value = "" Then
wsCopy.Range("A" & r.Row).Copy
'YOUR CODE DIDN'T SCROLL THE TABLE 2. USING DBLROW IN .Cells YOU CAN DO IT.
wsDest.Range("Table2").Cells(DblRow, 1).PasteSpecial
DblRow = DblRow + 1
End If
Next
End Sub
Edits highlighted by proper comments.
Report any question you have or bug you have encountered. If, according to your judgment, this answer (or any other) is the best solution to your problem you have the privilege to accept it (link).

How can I insert rows based on cell contents looped through all rows

I am trying to write a macro that tidies up and interrogates raw data exported from some analytical instrumentation. I would like it to look through one column (sample names) down all rows and look for indicators of specific sample types e.g. duplicates. Finding these indicators I want to insert a row, and in the new inserted row do some simple calculations based on the two rows above. For now I will just be happy getting the row insertion to work.
I can get it to find the key word and insert 1 row, but it finds the first one and stops. There are multiple instances of these keywords in my data, and i want to insert a row below each
'original code - finds first keyword, inserts row and stops
Sub dup_finder()
Dim colHeader As Range
Set colHeader = Range("B1:B500")
Dim currCell As Range
Set currCell = Cells.Find("*_dup")
If Not currCell Is Nothing Then currCell.Offset(1, 0).EntireRow.Insert Shift:=xlDown
End Sub
'my attempt to include loop - inserts 500 rows below keyword! stops
after first instance
Sub dup_finder()
Dim colHeader As Range
Dim row As Long
Dim currCell As Range
Set colHeader = Range("B1:B500")
Set currCell = Cells.Find("_dup")
For row = 1 To 500
If Not currCell Is Nothing Then currCell.Offset(1, 0).EntireRow.Insert Shift:=xlDown
Next row
End Sub
I suggest always fully qualifying your ranges with the workbook and sheet.
You should be able to adapt this to what you want. You simply enter the range you want to check in, and the value you are checking for.
It works backwards, up through the range, inserting a row below each one it finds.
Sub InsertRows()
''Declare your variables
Dim RngToCheck As Range, ValToFind As String
''Set the range in which to look for your desired string.
Set RngToCheck = ThisWorkbook.Sheets("Sheet1").Range("B1:B500")
''Set what string to look for.
ValToFind = "_dup"
''Declare a variable to use as a counter
Dim i As Long
''Count backwards through each of the rows in the range.
''(If you went forwards through the range, the rows you
''are inserting would become part of that range and push
''the bottom rows (which you intended to check) out of the range).
For i = RngToCheck.Rows.Count To 1 Step -1
''Check if the last characters (the number of characters to
''check is defined by the length of the string we are looking
''for) of the current cell match the string we are looking for.
If Right(RngToCheck(i).Value, Len(ValToFind)) = ValToFind Then
''Insert the row (we need to offset by 1 row
''because rows are inserted ABOVE, and we
''want it BELOW the current cell).
RngToCheck(i).Offset(1, 0).EntireRow.Insert
''Now you can add your formulas to the new row...
''column A
RngToCheck(i).Offset(1, -1).Formula = "=1+1"
''column B
RngToCheck(i).Offset(1, 0).Formula = "=2+2"
''column C
RngToCheck(i).Offset(1, 1).Formula = "=A" & RngToCheck(i).Offset(1, 1).Row & "+B" & RngToCheck(i).Offset(1, 1).Row
''column D
RngToCheck(i).Offset(1, 2).Formula = "Hello"
''And so on...
End If
Next i
End Sub
Assuming you do want to insert a row under every instance of a cell in column B containing "_dup" this should work.
The problem with your code was that it wasn't looping and so only ever found one instance.
It's advisable not to specify a fixed range as you are inserting rows and the range will expand; however, you could do this and set the search direction as "previous".
Sub dup_finder()
Dim colHeader As Range, s As String
Set colHeader = Range("B1:B500") ' not actually used
Dim currCell As Range
'are we searching just B or the whole sheet?
Set currCell = Columns(2).Find(What:="_dup", Lookat:=xlPart, MatchCase:=False, SearchFormat:=False) 'change parameters to suit
If Not currCell Is Nothing Then
s = currCell.Address 'store address of first found cell
Do
currCell.Offset(1, 0).EntireRow.Insert Shift:=xlDown
Set currCell = Columns(2).FindNext(currCell) 'find next case
Loop Until currCell.Address = s 'keep looping until we are back to the original case
End If
End Sub

Moving Data into destination sheet and formatting output

I have my data in columns A:L in Sheet2 and wish to copy each block based on the starting point, as certain cell text and the end point, again as certain cell text! The data is in columns A:L and move down down block by block
The code I have is very nearly 100% complete, but the last part I am trying to achieve is to put each item in a specific order on the destination sheet. As we know columns are A:L I want to paste my first block into Columns A:L in the destination then the next one in M:X then the final one in Y:AJ.
As there are about 10 of these blocks, Tank Engine, Weatherman etc I envisage, that I will need three blocks first, then a about three rows which are gaps before it is then repeated.
An example of this
The rows are dynamic but never more than 11 in length. The code I have is
Option Explicit
Sub MIKE3()
Dim wsSrc As Worksheet 'define source
Set wsSrc = ThisWorkbook.Worksheets("Sheet1")
Dim wsDest As Worksheet 'define destination
Set wsDest = ThisWorkbook.Worksheets("Sheet2")
Dim FindList As Variant 'defind search words
FindList = Array("Tank Engine")
Dim i As Long
Dim FindItm As Variant
For Each FindItm In FindList
Dim CopyRange As Range
Set CopyRange = FindMyRange(wsSrc.Range("A:L"), FindItm, "INFORMATION: " & FindItm)
If Not CopyRange Is Nothing Then
CopyRange.Copy wsDest.Range("A1").Offset(ColumnOffset:=i) 'note that if the first column uses merged cells the ColumnOffset:=i otherwise it is ColumnOffset:=i*12
i = i + 1
End If
Next FindItm
End Sub
Function FindMyRange(SearchInRange As Range, ByVal StartString As String, ByVal EndString As String) As Range
'find start
Dim FoundStart As Range
Set FoundStart = SearchInRange.Find(What:=StartString, LookAt:=xlWhole)
If FoundStart Is Nothing Then GoTo ERR_NOTHING_FOUND
find end
Dim FoundEnd As Range
Set FoundEnd = SearchInRange.Find(What:=EndString, LookAt:=xlWhole, After:=FoundStart)
If FoundEnd Is Nothing Then GoTo ERR_NOTHING_FOUND
Set FindMyRange = SearchInRange.Parent.Range(FoundStart, FoundEnd).Resize(ColumnSize:=12)
Exit Function'
ERR_NOTHING_FOUND:
FindMyRange = Nothing
End Function
thanks to PEH for his initial help and Thank you for looking!
I managed to make this work by editing the strings in my source data then writing x number of macros to cover my scenarios then calling them one by one in a module

Moving all cells into a new single column in Excel

I have an excel file like
Original File
I want to transform all the cells that filled with information into a single column. Like
To transform This
How to i do this ?
I searched in internet about that i found just only transform cells in a single row to a single cell. But i couldn't find anything like this. Can you help me about that
This is a bit of code I keep around for this kind of job. It assumes that the values in each row are contiguous, that is there are no blank cells inside the data set. It also assumes that you're on the sheet that contains the data when you trigger it, and that you want the data to be placed on a new worksheet.
Option Explicit
Sub Columnise()
Dim shtSource As Worksheet
Dim shtTarget As Worksheet
Dim rngRow As Range, rngCol As Range
Dim lCount As Long
Set shtSource = ActiveSheet 'Or specify a sheet using Sheets(<name>)
Set rngCol = Range("A1", Range("A" & Rows.Count).End(xlUp))
Set shtTarget = Sheets.Add 'Or specify a sheet using Sheets(<name>)
'Define starting row for the data
lCount = 1
'Loop through each row
For Each rngRow In rngCol
'On each row, loop through all cells until a blank is encountered
Do While rngRow.Value <> ""
'Copy the value to the target
shtTarget.Range("A" & lCount).Value = rngRow.Value
'Move one space to the right
Set rngRow = rngRow.Offset(0, 1)
'Increment counter
lCount = lCount + 1
Loop
Next rngRow
End Sub
You should end up with all the data in a single column on a new worksheet.
EDITED TO ADD: Since you mentioned your data does contain blank cells, it gets more complicated. We'll want to add a way to continue to the actual end of the data, rather than just looping until we hit a blank cell. We'll modify the Do While... condition to this:
Do While rngCell.Column <= Cells(rngCell.Row, Columns.Count).End(xlToLeft).Column
This will loop until the end of the data in the row, then move on. Give it a shot and let us know.

Pasting a range of cells onto a same size target range with special conditions?

Thanks for helping me out. I couldn't find a solution to this on the web so here a am :P. I am wondering how to paste a range of values, in this case C6:R371, to another worksheet in the same size. My problem is that I only want to paste data from the source worksheet into cells that are blank on the target worksheet and not change the values that are already in the range C6:R371 on the target worksheet. Essentially, I have a range of cells that i need to c&p, but i want the macro to only paste values from the range onto the blank cells of the target range. Thank you so much
Range("C6:S371").Select
Selection.Copy
wbWest2.Activate
Dim rng As Range
Dim row As Range
Dim cell As Range
Set rng = Range("D9:S374")
For Each row In rng.Rows
For Each cell in row.Cells
If cell.value = 0 then selection.paste
Next cell
Next row
Isolate the two worksheets using With ... End With statements so thier cells are the only ones that are considered. The fastest comparison would be bulk loading the two ranges into variant arrays.
Sub fill_blanks_from_source()
Dim r As Long, c As Long, aSRCs As Variant, aDSTs As Variant
With Worksheets("Sheet1") '<~~ source
aSRCs = .Range("C6:R371").Value2
End With
With Worksheets("Sheet2") '<~~ destination
aDSTs = .Range("D9").Resize(UBound(aSRCs, 1), UBound(aSRCs, 2)).Value2
End With
For r = LBound(aDSTs, 1) To UBound(aDSTs, 1)
For c = LBound(aDSTs, 2) To UBound(aDSTs, 2)
If Not CBool(Len(aDSTs(r, c))) Then
aDSTs(r, c) = aSRCs(r, c)
End If
Next c
Next r
With Worksheets("Sheet2")
.Range("D9").Resize(UBound(aDSTs, 1), UBound(aDSTs, 2)) = aDSTs
End With
End Sub
Once the comparisons have been met and blank values from the destination filled with values from the source, the entire variant array is returned to the destination worksheet.
The ranges will always remain the same size. Once the source values are loaded to the first variant array, the LBound and UBound functions are use for all further dimensioning of the destination range expanding from the cell in the top-left corner.

Resources