Trying to merge columns together in Excel - vba

I appreciate there are a lot of similar questions out there but I've been searching various forums for three days now and not yet found anything which does what I need - so either I'm doing something very strange or my searching skills aren't up to scratch!
I'd really appreciate it if someone could let me know where I'm going wrong, or even link me to a solution which might help as I haven't managed to find one.
I currently have a spreadsheet with six worksheets. Worksheets 2-6 contain data on items which have been sold from different sources. Worksheet 1 currently contains four columns which populate the item data using a macro I've cobbled together into four separate columns. Worksheet 2 contains an 'itemlist' column into which I want to copy the data from each of the four columns in worksheet 2.
I hope this makes sense. At the moment, the code I have is below:
Sub UpdateList()
'Clear the current ranges
Range("PharmacyItems").Clear
Range("PrelabelItems").Clear
Range("RestockItems").Clear
Range("TakehomeItems").Clear
Range("FullItemList").Clear
'Populate control with unique list
Range("PharmacyFullList").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("PharmacyItems"), Unique:=True
Range("PrelabelFullList").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("PrelabelItems"), Unique:=True
Range("RestockFullList").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("RestockItems"), Unique:=True
Range("TakehomeFullList").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("TakehomeItems"), Unique:=True
'Combine the four ranges into one
Range("UniqueLists!$A:$A, UniqueLists!$B:$B, UniqueLists!$C:$C, UniqueLists!$D:$D").Copy Sheets("Drug totals").Range("A2")
'Sort the data
Range("FullItemList").Sort Key1:=Range("FullItemList").Columns(1), Order1:=xlAscending, Orientation:=xlSortColumns, Header:=xlYes, SortMethod:=xlPinYin, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, DataOption2:=xlSortNormal
End Sub
In order to clarify the above, here is a definition of which range is which:
PharmacyItems, PrelabelItems, RestockItems and TakehomeItems: these are the individual lists which contain the unique items copied from each data worksheet.
FullList: the fulllist of the above four are the source data lists which are not unique lists
FullItemList: the column into which I want all the data from the unique lists to end up
The reason I have a range which specifies each column rather than using a named range is that I was trying to see if this would make it any better as originally it was just giving me a vague and fluffy range issue error. With the columns defined in the range it tells me the size/shape of the destination doesn't match the source.
The exact error is:
Run-time error '1004':
The information cannot be pasted because the Copy area and the paste area are not the same size and shape. Try one of the following:
- click a single cell, and then paste
- select a rectangle that's the same size and shape, and then paste
Can anyone help me? Sadly I'm a SQL Server girl, I'd far rather be pulling data from a database but I'm not allowed on this one!
Thank you in advance
Summer

You can't paste an entire column to a range starting on row 2 (or any other row than 1) because then the last row(s) of the column won't fit on the sheet. That's why Excel says "the Copy area and the paste area are not the same size".
Instead of
Range("UniqueLists!$A:$A, UniqueLists!$B:$B, UniqueLists!$C:$C, UniqueLists!$D:$D").Copy Sheets("Drug totals").Range("A2")
try pasting it starting on the first row.
Range("UniqueLists!A:D").Copy Sheets("Drug totals").Range("A1")
But I'm guessing you don't have data all the way down to the very bottom of your "UniqueLists" sheet? If so, then why are you copying the entire column? Just copy the part you need. Then you'll be able to paste starting on cell "A2". Example:
Range("UniqueLists!A1:D1234").Copy Sheets("Drug totals").Range("A2")

If you don't need the individual unique lists but just want to create a single column of all the unique values then this should work for you (untested though...)
Sub UpdateList()
Range("FullItemList").Clear 'Clear the full item list range
'Populate control with unique list
UniquesToFullItemList Range("PharmacyFullList")
UniquesToFullItemList Range("PrelabelFullList")
UniquesToFullItemList Range("RestockFullList")
UniquesToFullItemList Range("TakehomeFullList")
'Sort the data
Range("FullItemList").Sort Key1:=Range("FullItemList").Columns(1), _
Order1:=xlAscending, Orientation:=xlSortColumns, Header:=xlYes, _
SortMethod:=xlPinYin, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, _
DataOption2:=xlSortNormal
End Sub
Sub UniquesToFullItemList(rngFrom As Range)
rngFrom.AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=Sheets("Drug totals").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0), _
Unique:=True
End Sub

Related

How to copy filtered data without copying empty cells

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

Auto sorting and Merging of the cells using vba in excel

I have autosorted two of my rows using VBA in excel.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("C:D")) Is Nothing Then
Range("C3").Sort Key1:=Range("C4"), _
Order1:=xlAscending, _
Key2:=Range("D4"), _
Order2:=xlAscending, _
Header:=xlYes, _
OrderCustom:=2, MatchCase:=False, _
Orientation:=xlTopToBottom
End If
End Sub
I have auto sorted column C and D in ascending order.
But when i merge 2 cells in Column J (i.e. J53 and J54) the auto sorting does not work for the Column C and D or the entire sheet we can say.
I want to merge the cells in Column J as well as make Column C and D auto sort using VBA.
NB: similarly i want to sort to 2 cells in Column K as well.
Sorting does not work with merged cells. Except when all merged cells are the same size.
I highly recommend not to use On Error Resume Next without proper error handling. It just makes you blind to any errors but they still occur, you will just never know because the message is suppressed.
That is also why you didn't see the error message telling you exactly this! Remove On Error Resume Next and you will see the error message!
Solution
You can unmerge the cells to sort them, or use a 3ʳᵈ party tool like Kutools: How To Sort Data With Merged Cells In Excel?
Note that this is not the only case why merged cells are evil. Therefore I recommend not to use merged cells at all.
I would unmerge the cells, then sort and then merge again...

Sorting a range, Excel says range is empty

I try to sort a range (containing 3 columns) I want to sort the data on the second column and if there are two things the same in that column I want it to sort it via the first column.
The second and the first column are always filled in.
Here is the line I use, but I keep getting the error:
Runtime error 1004: The sort reference is not valid, make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank
Target.Sheets("SheetToSort").Range("A1:C" & m).Sort Key1:=Range("B1:B" & m), Order1:=xlAscending, key2:=Range("A1:A" & m), order2:=xlAscending
Target is a defined workbook, the sheet exists, cells "A1:C" & m contain data only column C might have empty spaces but I don't sort anything on that column.
Thanks for your help!
I'd just make sure all your ranges refer to the same sheet, so amend it like this:
Target.Sheets("SheetToSort").Range("A1:C" & m).Sort _
Key1:=Target.Sheets("SheetToSort").Range("B1:B" & m), Order1:=xlAscending, _
Key2:=Target.Sheets("SheetToSort").Range("A1:A" & m), Order2:=xlAscending
I know I've had issues before where this has happened because the Range object, when you don't specify the sheet, might be pointing to a different sheet than you think.

Excel VBA - AdvancedFilter

I am trying to filter a range dynamically in VBA and the VBA I am using is not working but I cannot see a logical reason as to why. To explain, I have a range of data in a sheet entitled "Full Stock Report" the size of which will change but I've set it statically in this example... And I'm trying to filter it by a list of criteria held in a range on a sheet initiated "Spitfire Aval Locations", again this is also dynamic but I've set as static again in this example. This sounds simple to me but the below line of code applies a filter but with no results (I have checked I know there are lots that should appear from this filter).
My second question is related, how does this VBA statement dictate which column in the range is being filtered ? (I fear this may be my issue ....)
Sheets("Full Stock Report").Range("A1:F20623").AdvancedFilter Action:=xlFilterInPlace,
CriteriaRange:=Sheets("Spitfire Aval Locations").range("A2:A228"), Unique:=False
Think I've solved this ... essentially AdvancedFilter requires the criteria to be the same format and same column titles as your data set. Not hugeley helpful to me, but I can bodge it to work.
I also have a hunch that AutoFilter with specified criteria might be a better option...
The column to filter on is the first .Range that you call .AdvancedFilter on. The code you posted filters columns A through F. If you wanted to only filter based on values in column A, it would look more like this:
Sheets("Full Stock Report").Range("A1:A20623").AdvancedFilter _
Action:=xlFilterInPlace, _
CriteriaRange:=Sheets("Spitfire Aval Locations").Range("A2:A228"), _
Unique:=False

Excel VBA Wrong copy with Advanced Filter

Im trying to get a list of unique data through the Advanced Filter option in Excel.
So, I recorded the macro I wanted to do and I got this as the code:
Sheets("Totaal").Range("A3:A65000").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range( _
"D2"), Unique:=True
This should be fine as far as I know because I did this a few times. Problem is, with this one, he only copies the first element to the selected Range. (I tried with actually giving it a range but that didn't change anything).
So, only copying first element not the whole array. If I do it manually it works.
Stumbled onto this one, very interesting problem. I created a test sheet to mimic yours that looked like:
The following code dropped all of the unique entries into col D starting at row 2:
Option Explicit
Sub Test()
Dim TotaalSheet As Worksheet
'set worksheet for easy reference
Set TotaalSheet = ThisWorkbook.Worksheets("Totaal")
'apply the advanced filter to get uniques
With TotaalSheet.Range("A3:A65000")
.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=TotaalSheet.Range("D2"), Unique:=True
End With
End Sub
Here are the results:
nothing is copied if the one of many empty cells on top of the range.