excel countif with user input variables - excel

new to VBA so please be gentle.....
I have a script that check for duplicates and inserts a count in a column, this works fine however the sheets are often different so I need to ask the user which column to check for duplicates and which column to insert the count. I've modified the script, but I'm only getting zero's entered into the destination column. I can't see what's going wrong. Any help would be great. Thanks in advance.
Sub LookForDuplicates()
Dim LastRow As Long
Dim column1 As String
'display an input box asking for column
column1 = InputBox( _
"Please enter column to ckeck")
'if no file name chosen, say so and stop
If Len(column1) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
Dim column2 As String
'display an input box asking for column
column2 = InputBox( _
"Please enter column to insert results")
'if no file name chosen, say so and stop
If Len(column2) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
'-------------------------------------------------------
'This is the original version of my script with set columns which works great..... However I need the user to specify the column to checck and also which column the results will be entered.
'LastRow = Range("B" & Rows.Count).End(xlUp).Row
' With Range("E1")
' .FormulaR1C1 = "=COUNTIF(C2,RC[-3])"
' .AutoFill Destination:=Range("E1:E" & LastRow)
' Range("E1").Select
' ActiveCell.FormulaR1C1 = "Duplicates"
'-----------------------------------------------------
LastRow = Range(column1 & Rows.Count).End(xlUp).Row
With Range(column2 & "1")
.FormulaR1C1 = "=COUNTIF(C2,RC[-3])"
.AutoFill Destination:=Range(column2 & "1" & ":" & column2 & LastRow)
Range(column2 & "1").Select
ActiveCell.FormulaR1C1 = "Duplicates"
End With
End Sub
I cannot get this working with the user input variables, apologies if I'm missing something but I can't find any resources on this....
The formula: =COUNTIF($B:$B,B2) works except when in the macro.
I need to add this line to the macro replaced with variables from user input like: =COUNTIF($column1:$column1,column12) but I keep getting syntax errors.
Thanks.

If you are expecting a String/Text value from your input box then you should specify it,
Dim column1 As String
'display an input box asking for column
column1 = InputBox("Please enter column to ckeck", "Range to Check", , , , 2)
Instead of juggling with a String here, why don't you just use the Range object where user can simply click on either full range or one cell in that column you want to check..
Using a range to get the inputbox data: You main issue seems to be setting range to check column in formula.
Option Explicit
Sub LookForDuplicates()
Dim LastRow As Long, StartRow as Long
Dim column1 As Range, column2 As Range
Set column1 = Application.InputBox("Please enter _
column to ckeck", "Range to Check", , , , , , 8)
If column1 Is Nothing Then
MsgBox "No column entered"
Exit Sub
End If
Set column2 = Application.InputBox("Please _
enter column to insert results", _
"Range to Output Results", , , , , , 8)
If column2 Is Nothing Then
MsgBox "No column entered"
Exit Sub
End If
LastRow = Cells(Rows.Count, column1.Column).End(xlUp).Row '--updated here
StartRow = column2.Row '-- here a new code added, assuming that you will have at least one row for column titles
With column2
.FormulaR1C1 = "=COUNTIF(R" & column1.Row _
& "C[-1]:R" & LastRow + 2 & "C[-1],RC[-1])"
.AutoFill Destination:=column2.Resize(LastRow - StartRow, 1)
End With
column2.Offset(-1, 0).FormulaR1C1 = "Duplicates"
End Sub
Output:

Solution if anybody else might find this useful:
The issue was even though column 1 was entered as a Column Reference H for example the COUNTIF function required this as a numeric reference so added an extra variable on the column1 value to the numeric value and modified the formula to suit. All working now:
Dim LastRow As Long
Dim column1 As String
'display an input box asking for column
column1 = InputBox( _
"Please enter column to ckeck")
'if no file name chosen, say so and stop
ColumnNumber = Columns(column1).Column
If Len(column1) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
Dim column2 As String
'display an input box asking for column
column2 = InputBox( _
"Please enter column to insert results")
'if no file name chosen, say so and stop
If Len(column2) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
LastRow = Range(column1 & Rows.Count).End(xlUp).Row
With Range(column2 & "1")
.FormulaR1C1 = "=COUNTIF(C" & ColumnNumber & ",C" & ColumnNumber & ")"
.AutoFill Destination:=Range(column2 & "1" & ":" & column2 & LastRow)
Range(column2 & "1").Select
ActiveCell.FormulaR1C1 = "Duplicates"
End With
End Sub

Related

Create rows and merge the first three columns

I'd like to have button in excel that insert a row and then merge the first three columns as well.
below is my code. It makes the row but it doesn not merge the columns. I just started VBA today so I assume it might be a syntax error.
Can someone assist pls?
Cheers
my vba code:
Sub AddRow()
Dim rowNum As Integer
On Error Resume Next
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM")
Rows(rowNum & ":" & rowNum).Insert Shift:=xlDown
Range("A(rowNum):A(rowNum + 1)").Merge False
End Sub
You can try this one too.
This function accepts only numeric values for the row number. If you enter any other character, the pop up box will say, "Number is not valid", and the InputBox will stay and not end the function until you enter a number (you can click on x if you want to cancel).
Sub add_rows()
row_number = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM", Type:=1)
ThisWorkbook.Sheets("Sheet1").Rows(row_number).Insert
Rng = "A" & row_number & ":" & "C" & row_number
ThisWorkbook.Sheets("Sheet1").Range(Rng).Merge
ThisWorkbook.Sheets("Sheet1").Range(Rng).HorizontalAlignment = xlCenter
End Sub
Something like this:
Sub AddRow()
Dim ws As Worksheet, rowNum As Long 'use Long instead of Integer
On Error Resume Next 'ignore error if user doesn't enter a number
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM")
On Error GoTo 0 'stop ignoring errors
If rowNum = 0 Then
MsgBox "A numeric value is required!", vbExclamation
Exit Sub
End If
Set ws = ActiveSheet
ws.Rows(rowNum).Insert Shift:=xlDown
ws.Cells(rowNum, "A").Resize(1, 3).Merge
End Sub

Matching data in excel from one worksheet to another

Currently I have a macro function using vba in excel that takes a row of data when you input it with a specific number. For example, I search 0.55 it will then search through "sheet 2" and paste the entire row that has 0.55 in "sheet 1".
What I would like is for it not to search an individual number, but a set of numbers found in sheet and then paste the corresponding data (full row) from sheet 2 next the data is sheet one.
Visual:
Sheet 1 sheet 1
Highlighted numbers are the ones I want found from sheet 2 (and only those)
The result would look like this:
Desired result
Where the data on the right is from sheet 2.
Current code:
Sub myFind()
'Standard module code, like: Module1.
'Find my data and list found rows in report!
Dim rngData As Object
Dim strDataShtNm$, strReportShtNm$, strMySearch$, strMyCell$
Dim lngLstDatCol&, lngLstDatRow&, lngReportLstRow&, lngMyFoundCnt&
On Error GoTo myEnd
'*******************************************************************************
strDataShtNm = "Sheet2" 'This is the name of the sheet that has the data!
strReportShtNm = "Sheet1" 'This is the name of the report to sheet!
'*******************************************************************************
Sheets(strReportShtNm).Select
Application.ScreenUpdating = False
'Define data sheet's data range!
Sheets(strDataShtNm).Select
With ActiveSheet.UsedRange
lngLstDatRow = .Rows.Count + .Row - 1
lngLstDatCol = .Columns.Count + .Column - 1
End With
Set rngData = ActiveSheet.Range(Cells(1, 1), Cells(lngLstDatRow, lngLstDatCol))
'Get the string to search for!
strMySearch = InputBox("Enter what to search for, below:" & vbLf & vbLf & _
"Note: The search is case sensitive!", _
Space(3) & "Find All", _
"")
'Do the search!
For Each Cell In rngData
strMyCell = Cell.Value
'If found then list entire row!
If strMyCell = strMySearch Then
lngMyFoundCnt = lngMyFoundCnt + 1
ActiveSheet.Rows(Cell.Row & ":" & Cell.Row).Copy
With Sheets(strReportShtNm)
'Paste found data's row!
lngReportLstRow = .UsedRange.Rows.Count + .UsedRange.Row
ActiveSheet.Paste Destination:=.Range("A" & lngReportLstRow).EntireRow
End With
End If
Next Cell
myEnd:
'Do clean-up!
Application.ScreenUpdating = True
Application.CutCopyMode = False
Sheets(strReportShtNm).Select
'If not found then notify!
If lngMyFoundCnt = 0 Then
MsgBox """" & strMySearch & """" & Space(3) & "Was not found!", _
vbCritical + vbOKOnly, _
Space(3) & "Not Found!"
End If
End Sub
Thank you so much in advance

applying formula in the column

I have a formula looking for the column "NAME", adding a blank column after it and naming this new column "word count". Now I need to apply following formula in the new column:
=TRIM(LEN(E2)-LEN(SUBSTITUTE(E2," ","")))+1
Column E is the "NAME" column; however, the location of this column might change from file to file.
Please, try the next code. It searches for the column header "NAME". in the first row of the active sheet and place the formula referencing the found column, in the second column after the found one:
Sub ApplyFormula()
Dim strColName As String, colRng As Range, lastR As Long, colLetter As String
strColName = "NAME" 'the header to search for
'Supposing that the columns headers are in the first row:
Set colRng = ActiveSheet.rows(1).Find(what:=strColName, LookIn:=xlValues, Lookat:=xlWhole)
If Not colRng Is Nothing Then
colLetter = Split(colRng.Address, "$")(1)
lastR = cells(rows.count, colRng.Column).End(xlUp).row
Range(colRng.Offset(1, 2), cells(lastR, colRng.Column + 2)).Formula = _
"=TRIM(LEN(" & colLetter & "2)-LEN(SUBSTITUTE(" & colLetter & lastR & ","" "","""")))+1"
Else
MsgBox "No """ & strColName & """ in the first row..." & vbCrLf & _
"Please, change the row (in the code) or search an existing header.", vbInformation, _
"No such column header..."
End If
End Sub

Using Input box for all variables in countif vba

I have tried to code a macro where a search is conducted for a specific text.
A)The column to search in,
B)The column where the result should appear and
C) The text for which the search is being conducted
All are referred by respective input boxes.
The input box for columns to be searched and where output is to be placed should only need the column name,(and not range) indicated by letters (text and so string) as value.
For example, if a search in column Y is to be done the input box should only need entry of letter "Y".
I have tried various permutations, but could not replace Y2:Y&LastRow in the code below, so that it refers to the input from input box for the column to search in.
The code is as follows:-
Sub CountIfAllVariablesFromInputBox()
Dim LastRow As Long
Dim ChkColumn As String
'display an input box asking for column
ChkColumn = InputBox( _
"Please enter column to check")
'if no input stop
ColumnNumber = Columns(ChkColumn).Column
If Len(ChkColumn) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
Dim InputColumn As String
'display an input box asking for column
InputColumn = InputBox( _
"Please enter column to insert results")
'if no input stop
If Len(InputColumn) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
'inputbox for text string to search for
Dim SuccessKeyWord As String
SuccessKeyWord = InputBox(Prompt:="Enter KeyWord For Success", _
Title:="KeyWord For Success", Default:="WOW!!")
LastRow = Range(ChkColumn & Rows.Count).End(xlUp).Row
Range(InputColumn & "1").Formula = "=COUNTIF(Range("Y2:Y"&LastRow),""" & SuccessKeyWord & """)"
End With
End Sub
Googling threw up so many ways to refer to ranges (with cells, cell, variables) that I am overwhelmed, unfortunately I could not get result by any of those.
I would be really thankful of your kind help.
I have posted a screenShot.sometimes I may need to search in column "W" and at others in column "Y". I need that flexibility by using the inputbox.
Screen Shot of the columns
Error after replacing the last line of the code by:-
Range(InputColumn & "1").Formula = "=COUNTIF(Range(""" & ChkColumn & 2 & ":" & ChkColumn & """&LastRow),""" & SuccessKeyWord & """)"
or
Range(InputColumn & "1").Formula = "=COUNTIF(Range(""" & ChkColumn & 2 & ":" & ChkColumn &LastRow & """),""" & SuccessKeyWord & """)"
Note:-
Search in column W
Result in column AA
Text to search WOW!!
Assumed you want the user to select the columns
Sub CountIfAllVariablesFromInputBox()
Dim LastRow As Long, Rng As Range
Dim ChkColumn As Range
Dim InputColumn As Range
Dim SuccessKeyWord As String
'display an input box asking for column
Set ChkColumn = Application.InputBox("Please enter column to check", Type:=8)
'if no input stop
If Len(ChkColumn) = 0 Then
MsgBox "No column entered"
Exit Sub
End If
ColumnNumber = ChkColumn.Column
'display an input box asking for column
Set InputColumn = Application.InputBox( _
"Please enter column to insert results", Type:=8)
'if no input stop
If InputColumn Is Nothing Then Exit Sub
'inputbox for text string to search for
SuccessKeyWord = InputBox(Prompt:="Enter KeyWord For Success", _
Title:="KeyWord For Success", Default:="WOW!!")
LastRow = Cells(Rows.Count, ColumnNumber).End(xlUp).Row
Set Rng = Range(Cells(1, ColumnNumber), Cells(LastRow, ColumnNumber))
Cells(1, InputColumn.Column) = "=COUNTIF(" & Rng.Address & ",""" & SuccessKeyWord & """)"
End Sub
Some modification from your line code:
Sub CountIfAllVariablesFromInputBox()
Dim LastRow As Long
Dim ChkColumn As String
'display an input box asking for column
ChkColumn = InputBox( _
"Please enter column to check")
'if no input stop
On Error Resume Next
ColumnNumber = Columns(ChkColumn).Column
If Err.Description <> "" Then
MsgBox "No column entered or Something Error"
Exit Sub
End If
On Error GoTo 0
Dim InputColumn As String
'display an input box asking for column
On Error Resume Next
InputColumn = InputBox( _
"Please enter column to insert results")
'if no input stop
If Err.Description <> "" Then
MsgBox "No column entered or Something Error"
Exit Sub
End If
On Error GoTo 0
'inputbox for text string to search for
Dim SuccessKeyWord As String
SuccessKeyWord = InputBox(Prompt:="Enter KeyWord For Success", _
Title:="KeyWord For Success", Default:="WOW!!")
LastRow = Range(ChkColumn & Rows.Count).End(xlUp).Row
Range(InputColumn & "1").Formula = "=COUNTIF(Range(""" & ChkColumn & 2 & ":" & ChkColumn &LastRow & """),""" & SuccessKeyWord & """)"
'End With
End Sub
Oh, Finally got it working
Sub CountIfAllVariablesFromInputBox()
Dim LastRow As Long
Dim ChkColumn As String
Dim InputColumn As String
Dim SuccessKeyWord As String
Dim rng As Range
'display an input box asking for column
ChkColumn = Application.InputBox("Please enter column to check")
'if no input stop
On Error Resume Next
ColumnNumber = Columns(ChkColumn).Column
If Err.Description <> "" Then
MsgBox "No column entered or Something Error"
Exit Sub
End If
On Error GoTo 0
'display an input box asking for column
On Error Resume Next
InputColumn = Application.InputBox( _
"Please enter column to insert results")
'if no input stop
If Err.Description <> "" Then
MsgBox "No column entered or Something Error"
Exit Sub
End If
On Error GoTo 0
'inputbox for text string to search for
SuccessKeyWord = Application.InputBox(Prompt:="Enter KeyWord For Success", _
title:="KeyWord For Success", Default:="WOW!!")
LastRow = Range(ChkColumn & Rows.Count).End(xlUp).Row
Set rng = Range(ChkColumn & 2 & ":" & ChkColumn & LastRow)
Range(InputColumn & "1").Value = WorksheetFunction.CountIf(rng, SuccessKeyWord)
End Sub
Thanks #JvdV #chrisneilsen #user11982798 #Davesexcel

Check column if duplicate record exist in VBA-excel

I'm new to VBA Macro in Excel, and would just like to ask if there's any function for checking duplicate records in excel.
This line of code below removes duplicate referring to column A, but I don't want to actually remove it without user's confirmation, what I wanted to do is to ask for user's confirmation if he wants it to be removed or not, like a popup, and then this line would just execute, but I have no idea if there's a function for checking duplicates.
ActiveSheet.Range("$A$1:$D$38").RemoveDuplicates Columns:=1
Thanks in advance for your help.
Please try the following code. I've set script to make duplicate cell empty, but you can insert your own code.
Sub FindDuplicates()
Dim i As Long
Dim j As Long
Dim lDuplicates As Long
Dim rngCheck As Range
Dim rngCell As Range
Dim rngDuplicates() As Range
'(!!!!!) Set your range
Set rngCheck = ActiveSheet.Range("$A$1:$D$38")
'Number of duplicates found
lDuplicates = 0
'Checking each cell in range
For Each rngCell In rngCheck.Cells
Debug.Print rngCell.Address
'Checking only non empty cells
If Not IsEmpty(rngCell.Value) Then
'Resizing and clearing duplicate array
ReDim rngDuplicates(0 To 0)
'Setting counter to start
i = 0
'Starting search method
Set rngDuplicates(i) = rngCheck.Find(What:=rngCell.Value, After:=rngCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
'Check if we have at least one duplicate
If rngDuplicates(i).Address <> rngCell.Address Then
'Counting duplicates
lDuplicates = lDuplicates + 1
'If yes, continue filling array
Do While rngDuplicates(i).Address <> rngCell.Address
i = i + 1
ReDim Preserve rngDuplicates(0 To i)
Set rngDuplicates(i) = rngCheck.FindNext(rngDuplicates(i - 1))
Loop
'Ask what to do with each duplicate
'(except last value, which is our start cell)
For j = 0 To UBound(rngDuplicates, 1) - 1
Select Case MsgBox("Original cell: " & rngCell.Address _
& vbCrLf & "Duplicate cell: " & rngDuplicates(j).Address _
& vbCrLf & "Value: " & rngCell.Value _
& vbCrLf & "" _
& vbCrLf & "Remove duplicate?" _
, vbYesNoCancel Or vbExclamation Or vbDefaultButton1, "Duplicate found")
Case vbYes
'(!!!!!!!) insert here any actions you want to do with duplicate
'Currently it's set to empty cell
rngDuplicates(j).Value = ""
Case vbCancel
'If cancel pressed then exit sub
Exit Sub
End Select
Next j
End If
End If
Next rngCell
'Final message
Call MsgBox("Total number of duplicates: " & lDuplicates & ".", vbExclamation Or vbDefaultButton1, Application.Name)
End Sub
P.S. If you need to remove dulpicates only inside one column, you need to adjust rngCheck variable to that particular column.
P.P.S. In my opinion, it's easier to use conditional formatting.

Resources