Using Input box for all variables in countif vba - excel

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

Related

Combine Cells into a String, so they are searchable with input box

I am attempting to create an Excel sheet based on an already existing workbook. I can't change the format of the workbook, so I am stuck with what follows.
We are creating a system to use a hand scanner with barcodes containing staff names, for the purposes of tracking COVID testing.
Our workbook has one column for first name, one for last.
So B2 = Cluff, C2 = Aaron
How do I use an input box (for the scanner) that searches the string "Cluff, Aaron" (user input in the box, not the name specifically in the code) and returns the row with the data above?
Bonus points if it opens a new input box to enter the test UPC (another input looking for a string), and inputs into Column AA on the same row.
My knowledge of VBA is very limited.
I tried various edits to the following code:
Sub DualFind()
Dim vFind1 As String, vFind2 As String
Dim rFound As Range, lLoop As Long
Dim bFound As Boolean
Dim rLookIn1 As Range, rLookIn2 As Range
vFind1 = InputBox("Find What: First value?", "FIND FIRST VALUE")
If vFind1 = vbNullString Then Exit Sub
vFind2 = InputBox("Find What: Second value?", "FIND SECOND VALUE")
If vFind2 = vbNullString Then Exit Sub
If Selection.Areas.Count > 1 Then
Set rLookIn1 = Selection.Areas(1).Columns(1)
Set rLookIn2 = Selection.Areas(2).Columns(1)
Else
Set rLookIn1 = Selection.Columns(1)
Set rLookIn2 = Selection.Columns(2)
End If
Set rFound = rLookIn1.Cells(1, 1)
For lLoop = 1 To WorksheetFunction.CountIf(rLookIn1, vFind1)
Set rFound = rLookIn1.Find(What:=vFind1, After:=rFound, LookAt:=xlWhole)
If UCase(rLookIn2.Cells(rFound.Row, 1)) = UCase(vFind2) Then
bFound = True
Exit For
End If
Next lLoop
If bFound = True Then
MsgBox "Match found", vbInformation, "ozgrid.com"
Range(rFound, rLookIn2.Cells(rFound.Row, 1)).Select
Else
MsgBox "Sorry, no match found", vbInformation, "ozgrid.com"
End If
End Sub
From what I gather, it needs two separate inputs to search the columns. I need it to search two columns with one input. I imagine you'd have to compile columns B and C into a string, and then search it based on input from the box.
Not entirely sure if this is what you were after but hopefully it will at least give you some more ideas. I've written this so that the user inputs the search name in the format [first name] [last name], e.g. Aaron Cluff. I've assumed from what you've written that the last name is found in column 2 and the first name in column 3.
Sub Demo()
Dim SearchName As String
Dim UPC As String
Dim LastRow As Long
Dim Row As Long
Dim RowMatch As Long
Dim ColFirstName As Integer
Dim ColLastName As Integer
ColLastName = 2
ColFirstName = 3
SearchName = InputBox("Enter search name: e.g. Aaron Cuff", "Search")
If SearchName = "" Then Exit Sub
SearchName = Trim(SearchName)
LastRow = Cells(Rows.Count, ColLastName).End(xlUp).Row
For Row = 1 To LastRow
If StrComp(SearchName, Trim(Cells(Row, ColFirstName)) & " " & Trim(Cells(Row, ColLastName)), vbTextCompare) = 0 Then
RowMatch = Row
Exit For
End If
Next
If RowMatch = 0 Then
MsgBox "Search Name: " & StrConv(SearchName, vbProperCase) & vbNewLine & vbNewLine & _
"No Match Found", vbInformation, "Search Result"
Exit Sub
End If
UPC = InputBox("Enter Test UPC for " & StrConv(SearchName, vbProperCase) & ": ", "Input")
If UPC <> "" Then
Cells(RowMatch, "AA") = UPC
End If
End Sub
Here's one way to do the staff name lookup:
Dim ws As Worksheet
Dim rng As Range, m, staffName
Set ws = Worksheets("Staff")
staffName = "Cluff, Aaron"
m = ws.Evaluate("MATCH(""" & staffName & """,A1:A1000 & "", "" &B1:B1000,0)")
If Not IsError(m) Then
Debug.Print "Matched on row " & m
Else
Debug.Print "No match for " & staffName
End If

Inserting value in 2nd cell based on value in 1st cell

I am trying to write a script where as it reads down an entire column starting with E2 and if a cell in that column has a particular value (for this example, let's say A, E, I, O, or U) then it enters a value of "Y" in cell F2, however it continues this pattern until it runs out of filled cells in column E.
I understand the logic of
Dim ColE As String
For ColE = 2 To Rows.Count
Next i
If E1 = "A" Or "E" Or "I" Or "O" Or "U" Then F2 = "Y"
but how do i repeat that say all the way down the entire column of E until it runs out of filled cells in column E
Here is an easy way to implement a list of OR's:
Sub marine()
Dim s1 As String, s2 As String
s1 = "AEIOU"
For i = 2 To 25
If Range("E" & i).Value <> "" Then
If InStr(s1, Range("E" & i).Value) > 0 Then
Range("F" & i).Value = "Y"
End If
End If
Next i
End Sub
Suitable option here is using the select case command with an if-loop
for i = 2 to Cells(Rows.Count, 5).End(xlUp).Row '5 = Column E
Select Case Range("E"&i).value
Case "A", "E", "I", "O", "U"
Range("F"&i).value
End Select
next
Using Select Case allows you to also give different commands for other inputs in column E and is way easier to handle than if-conditions for your specific requirements.
Cells(Rows.Count, 5).End(xlUp).Row '5
This will return the row number of the last entry in the fifth column (column E). You can use it in the for-loop to iterate until the very last row.
Search Multiple Criteria
Copy the code into a standard module (e.g. Module1).
Carefully adjust the values in the constants section.
The Code
Option Explicit
Sub searchMultipleCriteria()
' Handle Errors
Const Proc = "searchMultipleCriteria"
On Error GoTo cleanError
' Define constants.
Const SheetName As String = "Sheet1"
Const FirstRow As Long = 2
Const CriteriaCol As Variant = "E" ' 1 or "A"
Dim CriteriaVals As Variant: CriteriaVals = Array("A", "E", "I", "O", "U")
Const ResultCol As Variant = "F" ' 1 or "A"
Const ResultVal As String = "Y"
Dim wb As Workbook: Set wb = ThisWorkbook
' Write values from Criteria Column Range to Criteria Array.
Dim ws As Worksheet: Set ws = wb.Worksheets(SheetName)
Dim rng As Range
Set rng = ws.Columns(CriteriaCol).Find("*", , xlFormulas, , , xlPrevious)
If rng Is Nothing Then GoTo EmptyColumn
If rng.Row < FirstRow Then GoTo NoRange
Set rng = ws.Range(ws.Cells(FirstRow, CriteriaCol), rng)
Dim Criteria As Variant: Criteria = rng.Value
' Write values from Result Column Range to Result Array.
Set rng = rng.Offset(, ws.Columns(ResultCol).Column - rng.Column)
Dim Result As Variant: Result = rng.Value
' Modify values in Result Array.
Dim i As Long, Curr As Variant
For i = 1 To UBound(Criteria)
' Note: 'Match' is not case-sensitive i.e. A=a...
Curr = Application.Match(Criteria(i, 1), CriteriaVals, 0)
If Not IsError(Curr) Then
Result(i, 1) = ResultVal
Else ' Maybe you wanna do something here...
'Result(i, 1) = "N"
End If
Next i
' Write values from Result Array to Result Range.
rng.Value = Result
' Inform user.
MsgBox "Data transferred.", vbInformation, "Success"
' Revert Settings (not utilized in this Sub)
CleanExit:
Exit Sub
' Not As Planned
EmptyColumn:
MsgBox "Looking in an empty column to define a range with values!?", _
vbExclamation, "'" & Proc & "': Empty Column"
GoTo CleanExit
NoRange:
MsgBox "Trying to define a range with an ending row lower than " _
& "the starting row!?", _
vbExclamation, "'" & Proc & "': No Range"
GoTo CleanExit
cleanError:
MsgBox "An unexpected error occurred in '" & Proc & "'!" & vbCr _
& "Run-time error '" & Err.Number & "':" & vbCr & Err.Description, _
vbCritical, "'" & Proc & "': Unexpected Error"
On Error GoTo 0
GoTo CleanExit
End Sub

add items in a combobox

I'm trying to add items from a file saved in path "C:\Users\se72497\Desktop" which contains in the 1st column of the sheet called "Departamentos" a series of values I want to add in the Combobox.
My combobox receive the name of dept.
Private Sub UserForm_Initialize()
Dim filename As Workbook
Set filename = Workbooks.Open("C:\Users\se72497\Desktop\Tablas_Macro.xlsx")
With filename.Sheets("Departamentos")
dept.List = Range("A2", .Range("A" & Rows.Count).End(xlUp).Value)
End With
End Sub
I've tried to execute this code but it returns me a run-time error:
Why vba returns me this error?
The .Value is in the wrong place. (Or you could say that the parenthesis is in the wrong place). Correcting this, you have:
.Range("A2", .Range("A" & Rows.Count).End(xlUp)).Value
With your current code, .Value is within the Range call, so you're trying to use the value of the cell, not the cell itself, as the 2nd argument.
You want it outside.
Otherwise, if the last cell's value is "foo", then your code is equivalent to
Range("A2", "foo")
which is most certainly not what you want.
So when you click pn your combo box data will get loaded,
' Pre-requisties name the cell A2 with variable rstart
Private Sub UserForm_Initialize()
Dim ws As Worksheet: Set ws = Worksheets("Departamentos")
Dim i As Integer: i = 0
Dim lRow As Long
Dim sAddress As String
On Error GoTo errhandling
If Me.nameofcombobox.Value = vbNullString Then
MsgBox "Select value to continue!"
Else
With ws
lRow = .Range("Departamentos").Rows.Count
'name the cell a2 as rstart
Do Until .Range("rStart").Offset(0, i).Value = Me.nameofcombobox.Value
i = i + 1
Loop
sAddress = .Range("rStart").Offset(0, i - 1).Address
.Range(sAddress & ":" & Left(sAddress, 4) & lRow).Value = .Range(sAddress & ":" & Left(sAddress, 4) & lRow).Value
End With
End If
On Error GoTo 0
MsgBox "Completed without errors", vbInformation, "Success"
FunctionOutput:
Set ws = Nothing
Exit Sub
errhandling:
MsgBox "The following error occurred: " & Err.Description, vbCritical, "Error"
Resume FunctionOutput
End Sub

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.

excel countif with user input variables

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

Resources