How to copy filtered data without copying empty cells - vba

Scenario
I have an excel sheet with a lot of values. I am using some macro to filter those values.
What I need
I need to copy only the filtered values from current sheet to another sheet. I am doing the following way
Sub filterCopy()
Selection.SpecialCells(xlCellTypeVisible).Copy
Sheets("Sheet2").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
Issue
The above code doing exactly what is supposed to do by copying only the visible cells. But the problem is, it is copying entire sheet including all the blank cells upto row number 1048480 and even more. But my data is only upto row number 12. How should I copy only the visible cells that contains data and not all those blank cells?
Pictures
Filtered Sheet
After copied filtered data to another sheet

Your code doesn't take into account the last cell in the vertical space, and actually copies everything in the A1 range.
The solution is first, to avoid Select as it provides low performance, then to use
Cells(Rows.Count, "A").End(xlUp).Row
to get the last row in the A column. This gives us
Sub filterCopy()
Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).SpecialCells(xlCellTypeVisible).Copy Sheets(2).Range("A1")
End Sub
To copy the full table with the filtered rows, then use
Sub filterCopy()
Sheets(1).UsedRange.SpecialCells(xlCellTypeVisible).Copy Sheets(2).Range("A1")
End Sub

Related

Compare Cell Data and Copy

I found this great snip of code and I am trying to manipulate it to work for me, but I just can't seem to get it. Unfortunately I haven't been able to get my head around it to fully understand it, which doesn't help. So I turn to you. I need to evaluate a column of cells and look for either similarities or differences. If a cell in sheet 1 column 1 is not the same as any of the cells in sheet 2 column 1, I want to copy the entire row into sheet 1 at the bottom of the used area. I've gotten this to the point where what you see will copy the correct first cell, but I can't manipulate it to copy the entire row. I think because of how the 'With' is structured but I need to try to stay away from doing loops since there is over 30k cells to evaluate.
Going down the road I will also be wanting to look for duplicates using the same method above, and if there is a duplicate, compare the adjacent cells for differences and if there is a difference, move the existing data into a comment and move the new data into the existing cell.
Any and all advice is, as always, very appreciated.
Sub Compare_Function()
Call Get_Master_Cell_Info
Application.ScreenUpdating = False
With Sheets("Update").Range(Cells(4, 1), Cells(Rows.Count, 1).End(xlUp)).Offset(, 1)
.Formula = "=VLOOKUP(A4,'New Master Data 6.1'!A:A,1,FALSE)"
.Value = .Value
.SpecialCells(xlCellTypeConstants, 16).Offset(, -1).Copy Sheets("New Master Data 6.1").Range("A" & Rows.Count).End(xlUp).Offset(1)
.ClearContents
End With
Application.ScreenUpdating = True
End Sub
Quick line by line breakdown
This just takes the entire used range from cells A4 to the last used cell in columnA then offsets it by one column so B4:Bx (x is the last used row in column A)
With Sheets("Update").Range(Cells(4, 1), Cells(Rows.Count, 1).End(xlUp)).Offset(, 1)
This puts the formula in all cells so it looks up A4,A5,A6, etc in master sheet, returns the value in the master sheet or an error if its not found. It then copies the values over so they are hardcoded in
.Formula = "=VLOOKUP(A4,'New Master Data 6.1'!A:A,1,FALSE)"
.Value = .Value
Specialcells looks for constants (all cells) and value 16 which means error cells (ie cells don't exist) offsets by -1 (so column A) and copies to new sheet column A at rows.count+1
.SpecialCells(xlCellTypeConstants, 16).Offset(, -1).Copy Sheets("New Master Data 6.1").Range("A" & Rows.Count).End(xlUp).Offset(1)
You might also want to do this after you .clearcontents so you don't get all the error cells in column B
to fix it just change the copied range to .entirerow so
.SpecialCells(xlCellTypeConstants, 16).entirerow.Copy Sheets("New Master Data 6.1").Range("A" & Rows.Count).End(xlUp).Offset(1)
You will also copy the errors in column B but with this structure there is no getting around that. Can always erase them from the master sheet after.
Also note this code will overwrite any data you have stored in column B.
One more note this code depends on the sheet update being active, it won't run otherwise since your cells function inside your range needs the worksheet explicitly stated, as does your rows.count. You would be better wrapping the whole thing in 2 withs, one for the sheet and one with the range (using .cells and .rows.counmt)

Copying until last row

I have multiple sheets and I want to copy their data to another workbook on the last empty row of it. The data has a random number of rows but a defined number of columns, and I am having trouble copying it (not all the sheet, only the rows that have data) and then pasting it to the last row of the final workbook. How should I do it? I have no clue at all...
Disclaimer: I don't want to use select of activesheet as I will have multiple workbooks open and this has brought me problems. Also, the data is continues, and in this I mean that there are no empty rows in the middle of it. Also, I don't think this will change anything but this code is running inside a loop so it copies all sheets from multiple files.
Thanks!
col is the column number you're trying to copy
For Each ws in Activeworkbook.worksheets
lastrow = ws.cells(ws.rows.count, col).end(xlup).row
'code to copy and paste
Next ws
I asume you have a handle to the worksheets, so you can use this code to copy the data:
Public Sub CopyAcross(oSheetFrom As Worksheet, oSheetTo As Worksheet)
Const DATA_START_ADDRESS As String = "$A$1"
oSheetFrom.Range(DATA_START_ADDRESS).CurrentRegion.Copy
oSheetTo.Range("A" & oSheetTo.Rows.Count).End(xlUp).PasteSpecial xlPasteAll
Application.CutCopyMode = False
End Sub
Assuming that the data to be copied has the same start address on each sheet, which is specified as DATA_START_ADDRESS

How to move to next blank cell?

I have data on multiple sheets in a workbook that I want copied all to one sheet in that same workbook. When I run the macro, I would like it to start by deleting the current data in the "iPage Data Export" sheet and then replacing it with data from the other sheets.
I want the process to occur one column at a time since I may not bring over everything. Right now I am trying to learn how to do just one column.
I was able to get it to copy all of the contents of a column from one sheet, but when it moves to the next sheet, it overwrites the existing data. In the end, I only get one sheets worth of data copied.
Here are my 4 problems:
How do I make it clear the data on this sheet before running the routine?
How can I make it start each copy function at the bottom of that row (i.e. after the last cell with a value)? I have tried many of the suggestions on this and other boards without success. I will admit I am not very experienced in this.
How can I make it copy to a particular column (currently it just seems to default to A.
How can I concatenate multiple columns during the paste function? I.e. what if I want it to insert: A2&", "B2 instead of just A2
Sub CombineData()
Dim Sht As Worksheet
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name <> "iPage Data Export" Then
Sht.Select
Range("C:C").Copy
Sheets("iPage Data Export").Select
ActiveSheet.Paste
Else
End If
Next Sht
End Sub
How do I make it clear the data on this sheet before running the routine?
Sht.Cells.ClearContents
How can I make it start each copy function at the bottom of that row (i.e. after the last cell with a value)? I have tried many of the suggestions on this and other boards without success. I will admit I am not very experienced in this.
Range("C" & Rows.Count).End(xlUp).Offset(1, 0)
In detail:
Rows.Count will return the number of rows in the sheet, so in the legacy style *.xls workbooks this would return the number 65,536. Therefore "C" & Rows.Count is the same as C65536
Range("C" & Rows.Count).End(xlUp) is the same as going to C65536 and pressing Ctrl + ↑ - The command End(xlDirection) tells the program to go the last cell in that range. In this case, we would end up at the last cell containing data in column C.
.Offset(1, 0) means that we want to return the range offset by an amount of rows and/or columns. VBA uses RC (Rows Columns) references, so whenever you see something like the Offset() function with two numbers being passed as the arguments, it usually relates to the row, and the column, in that order. In this case, we want the cell that is one row below the last cell we referenced.
All-in-all the phrase Range("C" & Rows.Count).End(xlUp).Offset(1, 0) means go to the last cell in column C, go up until we hit the last cell with data, and then return the cell below that - which will be the next empty cell.
How can I make it copy to a particular column (currently it just seems to default to A.
Range("C:C").Copy Destination:=Sheets("iPage Data Export").Range("A:A")
You can pass the Destination argument in the same line and actually bypass the clipboard (faster and cleaner)
How can I concatenate multiple columns during the paste function? I.e. what if I want it to insert: A2&", "B2 instead of just A2
Lets say you wanted to reference column A, B, and F - just use:
Range("A1, B1, F1").EntireColumn
To summarise, you could streamline your existing code to something like (untested):
Sub CombineData()
Dim Sht As Worksheet
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name <> "iPage Data Export" Then
Sht.Range("C1:C" & Cells(Sht.Rows.Count, 3).End(xlUp).Row).Copy Destination:=Sheets("iPage Data Export").Range("A:A")
End If
Next
End Sub
This should do for the copying:
Sub CombineData()
Dim sheet As Worksheet
For Each sheet In Worksheets
If (sheet.Name <> "iPage Data Export") Then
sheet.Select
Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Worksheets("iPage Data Export").Activate
Cells(1, ActiveCell.SpecialCells(xlCellTypeLastCell).Column + 1).Select
ActiveSheet.Paste
End If
Next
End Sub
For the concatenation you need to be more specific - but I guess you should open a new question with a clearer focus if you need specific help on that.

Run time Error - 438

I have the following code in which I am trying to copy data from one sheet to another in same workbook. When I run the code I get Runtime error -438
Sub Copy()
Sheets("Sheet1").Range("A1:D20").Copy
Sheets("Sheet2").Activate
Range("E1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
Try the following code. You should not rely on Activate and Select.
Sub ZCopy()
Sheets("Sheet1").Range("A1:D20").Copy
Sheets("Sheet1").Paste Destination:=Worksheets("Sheet2").Range("E1")
Application.CutCopyMode = False
End Sub
Interesting Reads
MSDN
How to avoid using Select in Excel VBA macros
Do you have a particular need for copy and paste? This can be slow and inefficient. If you're just copying data from one sheet to another, you can set the values of one range equal to the values of another range and avoid the whole thing.
Sheets("Sheet2").Range("E1:H20").Value = Sheets("Sheet1").Range("A1:D20").Value
This will set the range from cells E1:H20 on Sheet2 to the same values as those in the range A1:D20 on Sheet1, which is effectively a copy and paste. I should add that this will work only for the values themselves.
If there is specific formatting (or formulas) that you need copied and pasted, this method won't work.

Clear all data after copying it but leaving all functions and formulas

I'd like to either clear the sheet after copying the content of the cells but without deleting the Excel functions, or cut everything from the current region but again, leaving functions in columns H and I intact.
The code is as follows and works well but I don't know how to clear the sheet and leave the functions intact. The functions are in columns H and I
Sub archive_old_data()
'copy Admissions sheet into Archive sheet
Application.ScreenUpdating = False
MsgBox "Please make sure you've reviewed all patients before archiving data."
Worksheets("Admissions").Activate
Range("A1").CurrentRegion.Copy
Worksheets("Archive").Activate
Range("A2").End(xlDown).Offset(1, 0).Select
ActiveCell.PasteSpecial
Worksheets("Admissions").Activate
End Sub
I would appreciate some help.
I don't have to copy currentregion, I need whatever is in cells A2:E2, but the problem is that next time I copy it might be A2:E9, another time A11:E11
If you just want to remove all number-values from a range you can use:
Range("A1:D4").SpecialCells(xlCellTypeConstants, 1).ClearContents
To clear both text and numbers (but not formulas) use SpecialCells(xlCellTypeConstants, 3).
If you are not sure of the specific range then you might apply this to entire columns, or Cells for the entire sheet.
If there is the possibility that there won't be any values to delete then you should include some error-handling, otherwise the error 'No cells were found' appears.