Finding multiple criteria with VBA - vba

i have a user form has 2 textboxes named "date" and "shift" and button to trigger a code. also a have a excel file named data.xlsx has "sheet1" have A column dates added as 07/02/2017, B column shift added as A/B/C.
date.value = "07/02/2017"
shift.value = "C"
so what i want to do is to find the row number of A column contains "07/02/2017" and B column contains "C" in data.xlsx.

Try the code below to find the Shift row in Column B (using the Match function).
You should be able to make the modifications to make it work also for finding the date from date TextBox.
Code
Sub CommandButton1_Click()
' this code goes inside the command button (inside the User_Form module)
Dim ValToSearch
Dim MatchRes As Variant
ValToSearch = Me.shift.Value '<-- get the value to look for
With Worksheets("Sheet1")
MatchRes = Application.Match(ValToSearch, .Range("B:B"), 0)
If IsError(MatchRes) Then '<-- match not found
MsgBox "Not found"
Else
MsgBox "Found at row " & MatchRes
End If
End With
End Sub

Related

Clicking a hyperlink in Excel to set an auto filter on a different sheet

I have a detailed product order worksheet example table 2. and a summary worksheet supplier name and total value example Table 2.
I want to know is it possible when I click the hyperlink details will filter my detailed product order sheet under this supplier all order example table 3.
If anyone can do this for me it will be helpful for me
Table 1
Table 2
Table 3
You can use the Worksheet_FollowHyperlink event to detect when a hyperlink has been pressed. A hyperlink to a location within the document will have a SubAddress, and the text that you clicked on will be the TextToDisplay.
The following code will detect when you click a hyperlink to a worksheet and - if that worksheet has an autofilter - will filter the first column of the AutoFilter for the text that you clicked on.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim wsToFilter As Worksheet
On Error GoTo SubErr
If Right(Target.SubAddress, 3) = "!A1" Then 'Hyperlink is to a worksheet within this document
Set wsToFilter = ThisWorkbook.Worksheets(Replace(Target.SubAddress, "!A1", ""))
If wsToFilter.AutoFilterMode Then 'Hyperlink has an AutoFilter
wsToFilter.AutoFilter.ShowAllData 'Remove existing filters
wsToFilter.AutoFilter.Range.AutoFilter 1, Target.TextToDisplay 'Filter the First column for the text of the hyperlink
End If
Set wsToFilter = Nothing
End If
SubErr:
End Sub
Use the Worksheet.FollowHyperlink Event to filter the desired data.
Option Explicit
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox Cells(Target.Parent.Row, "A") 'returns the value of column A of the clicked link
'do your filter stuff here …
End Sub

Run time error 424 Object Required working with UserForm

I'm trying to link a user form I built in VBA editor for MS Excel 2010 to the data in an excel worksheet, but I'm getting a
run-time error 424: Object required.
I referred to the active worksheet explicitly in my code to try and remedy this, but it still comes up with the same error. My code is:
Private Sub GetData()
Dim r As Long
r = ActiveSheet.Range("B2").Value
If IsNumeric(RowNumber.Text) Then
r = CLng(RowNumber.Text)
Else
ClearData
MsgBox "Invalid row number"
Exit Sub
End If
If r > 1 And r <= LastRow Then
cboFilterResultId.Text = FormatNumber(Cells(r, 1), 0)
txtFolderPaths.Text = Cells(r, 2)
txtFileName.Text = Cells(r, 3)
txtDeletedDate.Text = Cells(r, 4)
txtReason.Text = Cells(r, 5)
txtcboAdd.Text = Cells(r, 6)
txtcboView.Text = Cells(r, 7)
txtcboChange.Text = Cells(r, 8)
DisableSave
ElseIf r = 1 Then
ClearData
Else
ClearData
MsgBox "Invalid row number"
End If
End Sub
Where RowNumber is a textbox where the user can enter the row number for the data they want.
Please help!
I rarely use ActiveSheet just in case that isn't the sheet I'm after. Generally better to be explicit which sheet you're referring to:
r=ThisWorkbook.WorkSheets("Sheet1").Range("B2")
Right, pulling data from a worksheet to a userform... as you haven't said which line your error occurs on and you haven't given us the code for ClearData or DisableSave I'll start from scratch.
Example Form Design
I create a blank userform and add three text boxes and a spin button to it:
txtRowNumber holds the row number that the data is pulled from.
TextBox1 and TextBox2 will hold my sample values.
In the Tag property of TextBox1 I enter 1 and in the Tag property of TextBox2 I enter 2. These are the column numbers that the data will be pulled from.
In reality I usually add extra stuff, for example, 8;CPER;REQD. I'd then use some code to pull it apart so it pastes in column 8, must have a percentage and is a required entry.
spnButton is used to quickly move up or down a row.
We'll need two procedures to populate the form from the given row number and to clear all controls on the form (ready for the next row to be brought in).
Any textbox or combobox that has something in it's Tag property is cleared:
Private Sub ClearForm()
Dim frmCtrl As Control
For Each frmCtrl In Me.Controls
If frmCtrl.Tag <> "" Then
Select Case TypeName(frmCtrl)
Case "TextBox", "ComboBox"
frmCtrl.Value = Null
Case Else
'Do nothing.
End Select
End If
Next frmCtrl
End Sub
Any control that has a Tag value (it's assumed the value is correct) is populated from the specified RowNumber and column (from the Tag value). The value is always taken from the sheet called MyDataSheet in the workbook containing the VBA code (ThisWorkbook) no matter which is currently active:
Private Sub PopulateForm(RowNumber As Long)
Dim frmCtrl As Control
For Each frmCtrl In Me.Controls
With frmCtrl
If .Tag <> "" Then
.Value = ThisWorkbook.Worksheets("MyDataSheet").Cells(RowNumber, CLng(.Tag))
End If
End With
Next frmCtrl
End Sub
Whenever txtRowNumber changes the form should update with values from the indicated row. To do this we'll need to clear the form of current data and then repopulate it:
Private Sub txtRowNumber_Change()
ClearForm
PopulateForm CLng(Me.txtRowNumber)
End Sub
The spin button should increase/decrease the value in .txtRowNumber. I've added checks that it doesn't go below 1. You should also add checks that it doesn't go higher than the last populated row.
Private Sub spnButton_SpinDown()
With Me
.txtRowNumber = CLng(.txtRowNumber) + 1
End With
End Sub
Private Sub spnButton_SpinUp()
With Me
If CLng(.txtRowNumber) > 1 Then
.txtRowNumber = CLng(.txtRowNumber) - 1
End If
End With
End Sub
Finally, the form should be populated when it is first opened:
Private Sub UserForm_Initialize()
With Me
.txtRowNumber = 2
.spnButton = .txtRowNumber
PopulateForm .txtRowNumber
End With
End Sub

VBA Form - Vlookup cell and assign value to that cell

Encountering an issue in a VBA regarding vlookup function.
I have 2 comboboxes and 6 Textboxs for user input.
I want to use a vlookup (or index,Match(),Match()) to look up a cell in a data table and assign the values from the textboxes to these cells.
When I run the code for what I believe should work, it is returning object errors.
Private Sub CommandButton2_Click()
Dim MonthlyTable As Range
Set MonthlyTable = Sheets("DATA Monthly").Range("A6:AE400")
Dim ColumnRef As Range
Set ColumnRef = Sheets("Drivers").Range("N11")
' Assign CB2 value to M11 cell reference so it can be converted to a column ref in N11.
Sheets("Drivers").Range("M11").Value = ComboBox2.Value
Dim CB1Value As String
CB1Value = "Joiners" & ComboBox1.Value
Dim CB2Value As String
CB2Value = ComboBox2.Value
MsgBox CB1Value & " " & CB2Value
Dim tb1value As Range
tb1value = Application.WorksheetFunction.VLookup(CB1Value, MonthlyTable, ColumnRef, False)
tb1value.Value = TextBox1.Value
Unload Me
End Sub
I am at a loss for what to do here as I feel like it should be this simple!
Thanks in advance.
Edit. Further digging indicates that you cannot select a cell you are vlookup'ing as this commands only returns a value it does not actually select the cell for my intents and purposes.
not really clear to me you actual aim, but just following up your desire as stated by:
I want to use a vlookup (or index,Match(),Match()) to look up a cell
in a data table and assign the values from the textboxes to these
cells
you may want to adopt the following technique:
Dim tb1value As Variant '<--| a variant can be assigned the result of Application.Match method and store an error to be properly cheeked for
tb1value = Application.Match(CB1Value, MonthlyTable.Column(1), 0) '<--| try finding an exact match for 'CB1Value' in the first column of your data range
If Not IsError(tblvalue) Then MonthlyTable(tb1value, columnRef.Value).Value = TextBox1.Value '<--| if successful then write 'TextBox1' value in data range cell in the same row of the found match and with `columnRef` range value as its column index
Excel uses worksheet functions to manipulate data, VBA has different tools, and when you find yourself setting cell values on a sheet via VBA so that some worksheet function can refer to them it is time to look for a true VBA solution. I suggest the following which, by the way, you might consider running on the Change event of Cbx2 instead of a command button.
Private Sub Solution_Click()
' 24 Mar 2017
Dim MonthlyTable As Range
Dim Rng As Range
Dim Lookup As String
Dim Done As Boolean
Set MonthlyTable = Sheets("DATA Monthly").Range("A2:AE400")
' take the lookup value from Cbx1
Lookup = ComboBox1.Value
Set Rng = MonthlyTable.Find(Lookup)
If Rng Is Nothing Then
MsgBox Chr(34) & Lookup & """ wasn't found.", vbInformation, "Invalid search"
Else
With ComboBox2
If .ListIndex < 0 Then
MsgBox "Please select a data type.", vbExclamation, "Missing specification"
Else
TextBox1.Value = MonthlyTable.Cells(Rng.Row, .ListIndex + 1)
Done = True
End If
End With
End If
If Done Then Unload Me
End Sub
There are two points that need explanation. First, the form doesn't close after a rejected entry. You would have to add a Cancel button to avoid an unwanted loop where the user can't leave the form until he enters something correct. Note that Done is set to True only when the search criterion was found And a value was returned, and the form isn't closed until Done = True.
Second, observe the use of the ListIndex property of Cbx2. All the items in that Cbx's dropdown are numbered from 0 and up. The ListIndex property tells which item was selected. It is -1 when no selection was made. If you list the captions of your worksheet columns in the dropdown (you might do this automatically when you initialise the form) there will be a direct relationship between the caption selected by the user (such as "Joiners") and the ListIndex. The first column of MonthlyTable will have the ListIndex 0. So you can convert the ListIndex into a column of MonthlyTable by adding 1.
I think it is better to use "find" in excell vba to select a cell instead of using vlookup or other methods.

How to collect data from multiple sheets by using sheet names

Thanks for the response!
however the code which you sent started from the beginning of the workbook. but it should not be.
For example, a workbook contains sheets (only user knows the sheet name, so we can't give the sheet name on the code) as following
Summary/Version/AA/BB/CC/DD/Final
If beginsheet=AA then the code should start collecting data from AA and if endsheet = DD then the code should stop collecting data at Final. Only till DD is valid.
So how can we achieve this.
You can do a FOR - EACH: For each theSheets in ActiveWorkbook.Sheets
For each theSheets in ActiveWorkbook.Sheets
Sheets(theSheets.Name).Select
msgbox(theSheets.Name)
next
I put the MSGBOX just to show the name of the sheet. Also the Select is not necessary I put it there just to show how it changes from sheet to sheet.
If you don't want to search all sheets (each sheet) but a specified number of sheets, you can assign the sheets names to a collection and the iterate that collection; in that case you have to know the names of the sheets.
sorry I did not get your first question...
Well, I don't know how practical this solution will be for you purpose but you could do the following:
When you open the workbook create CheckBoxes with the names of the Sheets:
Private Sub Workbook_Open()
Dim row As Integer
row = 14
For Each mysheets In ActiveWorkbook.Sheets
ActiveSheet.CheckBoxes.Add(20, row, 50, 20).Select
With Selection
.Caption = mysheets.Name
.Value = xlOff
.LinkedCell = "C" & ToRow
.Display3DShading = False
End With
row = row + 50
Next
End Sub
Have the users select the Sheets that apply.
Fill a collection with the "Text" of the selected CheckBoxes (which will be the names of the sheets)
Iterate through the sheets in the collection
Dim allSelectedSheets As New Collection
Public Sub FindSelectedCkBox()
For Each ckbox In ActiveSheet.CheckBoxes
If ckbox.Value > 0 Then
allSelectedSheets.Add ckbox.Text
End If
Next
iterateThroughSheets
End Sub
Sub iterateThroughSheets()
For Each theSheets In allSelectedSheets
ActiveWorkbook.Sheets(theSheets).Select
Next
End Sub
Make sure to remove the CheckBoxes when opening the Book so you don't end up with duplicates.

excel - find and highlight text from one sheet on second sheet

I am getting killed by excel, I'm not 100% sure it can do exactly what I'm needing. I've tried various functions and can come close, but none are perfect. I've uploaded a spreadsheet as an example. I have a sheet of mailboxes, followed by a cell with the users who have access to the mailbox. The cell has anywhere from 0 to 5 users separated by commas. The second sheet has a list of users. What I need is a way to parse out the first sheet, either highlight on the first sheet, or copy to another sheet; all the mailboxes that all the associated users match in the second cell appear on the second sheet.
The real world sheet I have has over 2500 mailboxes with as many as 205 (as few as 0) associated users, so I desperately need a way to mechanically filter the sheet. I'm trying to filter the mailboxes that all the associated users are present on a second sheet.
I've tried using vlookup, index/match and a few others, and what seems to trip it up is having the comma separation. Using ""& cell_i'm_looking_for &"" returns nothing so I'm guessing I need to try something else. I also have the sheet with all the users in separate cells.
I downloaded your sheet and created a module with the following function inside of it:
Function mymailboxes(who As Range, lookup As Range)
Dim myRow As Range
For Each myRow In lookup
If InStr(myRow.Cells(1, 2).Value, who.Value) > 0 Then
myReturn = myReturn & "," & myRow.Cells(1, 1).Value
End If
Next
'cut off the first ,
myReturn = Right(myReturn, Len(myReturn) - 1)
mymailboxes = myReturn
End Function
Then on Sheet 2, Cell E2 I gave the following formula: =mymailboxes(A2, Sheet1!A1:B50) which gave me the following results: mailbox1,mailbox2,mailbox4,mailbox8,mailbox12,mailbox17,mailbox21,mailbox25,mailbox28,mailbox34,mailbox39,mailbox41,mailbox42,mailbox44,mailbox49,mailbox50
I hope this helps.
To get a list of invalid users the following function will help.
Function get_invalid_users(users As Range, validusers As Range)
Dim myRow As Range
myusers = Split(users, ",")
myReturn = ""
For Each user In myusers
is_valid_user = False
'Guilty until proven innocent
For Each myRow In validusers
If myRow.Cells(1, 1).Value = user Then
is_valid_user = True
'Proven innocent, break out of the loop, no double jeopardy.
Exit For
End If
Next
If is_valid_user = False Then
myReturn = myReturn & "," & user
End If
Next
If Len(myReturn) > 0 Then
myReturn = Right(myReturn, Len(myReturn) - 1)
Else
myReturn = ""
End If
get_invalid_users = myReturn
End Function
Sheet 1, Cell C2 with formula: =get_invalid_users(B2, Sheet2!$A$1:$A$3) returned zx1234