Excel VBA RemoveDuplicates function with case sensitivity - vba

I'm trying to remove some duplicates from selected column, but the function removes all duplicates irrespective of the case. RemoveDuplicates considers lower case, upper case, etc as duplicate. E.g. the function removed CENTRAL, central and Central.
I have simply recorded the following code and only changed it a little bit. I need to keep items with different cases and don't want to remove as duplicates.
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+q
'
ActiveWorkbook.Sheets(3).Range("A:A").Clear
Selection.Copy
Sheets("Sheet3").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.RemoveDuplicates Columns:=1, Header:=xlNo
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Sheet2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
'Range("B12").Select
Selection.End(xlToRight).Select
ActiveWorkbook.Sheets(3).Range("A:A").Clear
End Sub

Try the following code using a Dictionary to remove duplicates with case sensitivity:
Option Explicit
Sub Test()
RemoveDuplicates Sheet1.Range("A1:A12")
End Sub
Sub RemoveDuplicates(rngDataColumn As Range)
'assumes rngDataColumn is a column of data
Dim dic As Object
Dim rngCell As Range
Dim varKey As Variant
Dim lngCounter As Long
'create dictionary
Set dic = CreateObject("Scripting.Dictionary")
'dictionary becomes case sensitive
dic.CompareMode = vbBinaryCompare
'iterate range for unique values
For Each rngCell In rngDataColumn
If Not dic.Exists(rngCell.Value) Then
dic.Add Key:=rngCell.Value, Item:=True
End If
Next rngCell
'clear source range
rngDataColumn.ClearContents
'output unique items - with case sensitivity
lngCounter = 1
For Each varKey In dic.Keys
rngDataColumn(lngCounter, 1).Value = varKey
lngCounter = lngCounter + 1
Next varKey
End Sub
A1:A12 in my test case is as follows:
So, to update your recorded macro, you could try:
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+q
'
ActiveWorkbook.Sheets(3).Range("A:A").Clear
Selection.Copy
Sheets("Sheet3").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
'use the new function here
RemoveDuplicates Selection
'Selection.RemoveDuplicates Columns:=1, Header:=xlNo
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Sheet2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
'Range("B12").Select
Selection.End(xlToRight).Select
ActiveWorkbook.Sheets(3).Range("A:A").Clear
End Sub

I have found here and tested some nice solution, that seems to meet your expectations. You have to paste this function into your project:
Option Compare Binary
Sub deleteExactDuplicates(ByVal rng As Range)
Application.ScreenUpdating = False
With CreateObject("scripting.dictionary")
For Each i In rng.Cells
v = i.Value
If .exists(v) Then
i.ClearContents
Else
.Add v, 1
End If
Next i
End With
On Error Resume Next
rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
Then, you have to call it in your code. If I understand, you want to remove duplicates from selected range, so the macro would look like this:
Sub test()
deleteExactDuplicates Selection
End Sub
Now, this solution delete not only the values in selected range, but also entire rows, where duplicated values occurred. Are you OK with that, or you need something that removes duplicates only from particular range?

Related

How to self reference a cell in VBA

I have 600k rows and want to remove starting and trailing whitespace. I have the following, but it is rather slow:
Sub Macro1()
'
' Macro1 Macro
'
'
Range("D1").Select
ActiveCell.FormulaR1C1 = "=TRIM(RC[-1])"
Range("D1").Select
Selection.AutoFill Destination:=Range("D1:D4")
Range("D1:D4").Select
Columns("D:D").Select
Selection.Copy
Range("C1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("D:D").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("C1").Select
End Sub
Is there a way that I can apply the function on itself. I would like to avoid running a function in an empty column, then copying the values to the original column.
I tried VBA to fill formula down till last row in column as well as to speed up the formula. I have a few columns to do this with, and wonder if it is possible to only work on column C and trim the whitespace without the extra computations.
Thanks
This does not use a second column and does all the values in Column C. It moves the values to an array, iterates the array and trims the excess space and overwrites the values in C with the array.
Sub macro1()
Dim rng As Variant
Dim ws As Worksheet
Dim i As Long
Set ws = Worksheets("Sheet1") 'Change to your sheet name.
With ws
rng = .Range("C1", .Cells(.Rows.Count, 3).End(xlUp)).Value
For i = LBound(rng) To UBound(rng)
rng(i, 1) = Application.Trim(rng(i, 1))
Next i
.Range("C1", .Cells(.Rows.Count, 3).End(xlUp)).Value = rng
End With
End Sub
Change the code like this so you don't use Select. Using Select and Selection slows everything down horribly.
Sub Macro1()
Range("D1").FormulaR1C1 = "=TRIM(RC[-1])"
Range("D1").AutoFill Destination:=Range("D1:D4")
Columns("D:D").Copy
Range("C1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Columns("D:D").ClearContents
End Sub

VBA for formula to values in a filtered range

Sometimes, I need to run a formula on a selection of a filtered range and then convert it to values, every time I want to copy and then special paste values, I must clear the filters first. I need a macro that will convert the formula to values without clearing the filters, I also want to use a shortcut key for this operation.
The code below will allow this operation, the CTRL+M shortcut is available for this operation. Edit the macro to assign this shortcut key.
Sub PasteFilterValues()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
If Selection.Cells.Count = 1 Then
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Else
Dim rng As Range
Set rng = Selection.SpecialCells(xlCellTypeVisible)
For Each cl In rng
cl.Copy
cl.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next cl
rng.Select
End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.CutCopyMode = False
End Sub
This should be faster than the other solution
Option Explicit
Sub fla2values(rng As Range)
Dim c As Range
For Each c In rng.SpecialCells(xlCellTypeVisible)
c.Value = c.Value
Next c
End Sub
Sub test_fla2values()
fla2values Selection
End Sub

Trying to copy specific columns in a row to another excel sheet based on it meeting certain criteria

Im very new to excel/vba and trying to use a macro to check a column for the value true, when it sees that value I'd like it to copy parts of that row to another sheet in my column. Then I need it to iterate through the other rows and perform the same checks. Here is my code currently.
Sub Macro3()
'
' Macro3 Macro
'
'
Sheets("Aspen Data").Select
Dim tfCol As Range, Cell As Object
Set tfCol = Range("G26:G56")
Sheets("Code").Select
ActiveSheet.Calculate
Sheets("Aspen Data").Select
ActiveSheet.Calculate
For Each Cell In tfCol
If IsEmpty(Cell) Then
Exit Sub
End If
If Cell.Value = "True" Then
Range("I26:Q26").Select
Selection.Copy
Sheets("AspenHist").Select
Range("B" & Rows.Count).End(xlUp).Offset(1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next
End Sub
The issue appears to be in getting my Range("I26:Q26) to increment by one as it goes through the loop.
Try this
Sheets("Aspen Data").Select
Dim i As Integer
Sheets("Code").Calculate
Sheets("Aspen Data").Calculate
For i = 26 To 56
If IsEmpty(Cells(i, 7)) Then
Exit Sub
ElseIf Cells(i, 7).Value = "True" Then
Range(Cells(i, 9), Cells(i, 12)).Copy
Sheets("AspenHist").Activate
Range("B" & Rows.Count).End(xlUp).Offset(1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Aspen Data").Activate
End If
Next i
There's no need to use .Select/.Activate/ActiveSheet (see this) to accomplish your goals, and you can definitely use For Each. Try this:
Option Explicit
Sub Macro1()
'
' Macro1 Macro
'
'
Dim tfCol As Range, Cell As Object
Set tfCol = Sheets("Aspen Data").Range("G26:G56")
Application.ScreenUpdating = False
Sheets("Code").Calculate
Sheets("Aspen Data").Calculate
For Each Cell In tfCol
If IsEmpty(Cell) Then
Exit For
End If
If Cell.Value = "True" Then
Sheets("Aspen Data").Range("I" & Cell.Row & ":Q" & Cell.Row).Copy
Sheets("AspenHist").Range("B" & Rows.Count).End(xlUp).Offset(1).PasteSpecial _
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
Next
Application.ScreenUpdating = True
End Sub

Calculate, Copy and Paste to a given value in VBA

I am fairly new to VBA. I am trying to automate iterations based on the no. of iterations specified in cell "E2". I want excel to Autofill down column A from cell "A4" to the value of cell "E2" e.g if E2 = 100, Excel will autofill series 1,2,3...down to 100.
I then want excel to continuosly calculate the value of cell "B2" then copy and paste each result down column B, starting at "B4" and stops at the value of iterations "E2"
I have the following code for the "Autofill"
Sub Monte3()
Dim srcRange As Range
Dim destRange As Range
Range("A5:A1000000").ClearContents
Set srcRange = ActiveSheet.Range("A4")
Set destRange = ActiveSheet.Range("A4:A103")
srcRange.AutoFill destRange, xlFillSeries
End Sub
I have recorded the following Macro for copy paste
Sub Macro10()
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
What's the easiest way to do this?
A nice For Each Next Loop should work. See the code below. I took some guesses on some of the range references based on what you wrote above, but you should be able to modify it easily to suit your needs.
Sub Monte3()
Dim srcRange As Range, cel As Range
Dim wks As Worksheet
Set wks = Sheets("Sheet1") 'replace Sheet1 with your sheet name
With wks
.Range("B5:B1000000").ClearContents
Set srcRange = .Range("B4:B" & .Range("E2").Value + 4) 'will plug the number in from E2 as the row and adds 4 since you are starting at row 4
For Each cel In srcRange
With .Range("B2")
.Calculate
.Copy
End With
cel.PasteSpecial xlPasteValues
Next
End With
End Sub

Need to copy & paste from several different sheets into one sheet vertically

I'm attempting to write a macro that will copy a range of cells from a sheet, paste them into a sheet ("Bulksheet") that will contain all pasted data, then move on to the next tab after the first sheet. This needs to be done for 40+ tabs. Luckily, the data is in the same place in each tab, including the Bulksheet tab.
I can easily get this to apply to one tab, but returning to the first active tab and then moving on to the next is giving me no end of trouble.
Ex. code (shortened to the crucial bit). At the bottom where Next is would be where I need to move to the next sheet and do the same function, returning to "Bulksheet" and pasting in the next empty cell in column C.:
Sub
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Activate
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next
End Sub
Try looping through the sheets using an index value instead.
Sub
Dim i as integer
For i = 1 to worksheets.count
sheets(i).Activate
if activesheet.name <> "Bulksheet" then
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
end if
Next
End Sub
Try this:
Sub CopyToBulksheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Bulksheet" Then
ws.Activate
Range("C1:F10").Copy
Sheets("Bulksheet").Select
Range("D" & Cells.Rows.Count).End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next
End Sub