Trying to use VBA-excel to filter one worksheet based on clicked value in another workseet - filter

OK, I'm a total VBA noob, so excuse my awful code.
I have two excel worksheets, one titled 'Contractors' and one titled 'Referring_to_Contractors'.
The contractors sheet is laid out like so.
Terr ContractorID First Last
1 7 Bob Smith
2 5 Jeff Brown
3 8 Stan Lee
The Referring_to_Contractors sheet has the same fields and layout as the Contractors sheet above, but also has additional columns for Referring Contractors, so it has columns titled "Ref_Contractor_Id", "Ref_First", "Ref_Last", etc.
What I'm trying to do is use VBA so that when someone double clicks a row in the "Contractors" sheet, it will take the value in the Contractor_ID column, then look in the "Referring_to_Contractors" sheet and filter by all records in that sheet that have that value as Contractor_ID. Essentially, this would display referral information for the Contractor_ID clicked on the first sheet. I created a named range for the Contractor_ID field titled "PrimaryContractor"
So, on the first sheet 'Contractors', I have:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
End Sub
and..
Sub Select_Ref_Contractors()
ContractorId = Range("PrimaryContractor").Value
With Sheets("Referring_to_Contractors")
.Visible = True
.Select
End With
ActiveSheet.Range("$B$10:$N$44163).AutoFilter Field: =1, Criteria1:= ContractorID
Application.Goto Range("A1"), True
End Sub
Conceptually this seems like it should be pretty simple yet for some reason I can't get the second sheet to filter correctly.
Any helps or even useful links would be greatly appreciated.

I have just knocked this up in Excel 2007 and it seems to work
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim id As String
If Not Target.Cells.Count > 1 Then
id = CStr(Selection)
Sheet2.Activate
Sheet2.Range("A1", "c4").AutoFilter 1, id
End If
End Sub
It is using the same table on both sheets as below and when you double click a cell on Sheet1, the BeforeDoubleClick event fires and puts you onto Sheet2 with the filter applied.
ID ID2 Text
1 2 a
2 2 b
3 3 c

Related

Excel for Mac VBA - Go to specific row of table and work up the rows to first row

I´d like to find a specific row of a table in Excel for Mac 2011. From this row, I want to work up the table to the 1st row. I´m sure there is a simple way of doing it.
Also, what is the tweak, to work down to the end of the table from a specified row?
Thanks in Advance!!
You might want to provide an idea of what you have tried...as well as how you want to find the starting row. Regardless, here I have finding the end row of your data (based on column A, change as needed). This goes to the bottom of the sheet, then essentially does Ctrl + up arrow to get the last row that has something in it. Then starts from there and steps backwards through the rows until row 1. Nb you don't have to set i to endRow, I just did in case you wanted to use endRow for something else.
Public Sub testing()
Dim ws As Worksheet
Dim endRow As Integer
Dim i As Integer
Set ws = ThisWorkbook.Worksheets("Sheet1")
endRow = ws.Range("A" & Rows.Count).End(xlUp).row
i = endRow
While i >= 1
'Working up the sheet doing whatever
i = i - 1
Wend
End Sub

Adding record via not in list event of combo box

Hopefully someone can help me with this.
On frmMain, I have a listbox (lstAuthor) and a combo box (cboAuthor). The RowSource for both is a query, qryListAuthor. Both have two columns, authorID and AuthorName, and the bound column is col 1.
When I start typing the author name in the combo box, I want it to update and when the author I am looking for fills in the current line I am typing, I want to press enter and have the lstAuthor update to that particular record, and be selected.
Plus another listbox called lstBook, to update and show the books written by the author selected in lstAuthor. This is currently happening if I scroll down the list of authors in lstAuthor and select one.
Not in list:
If I am typing the author name in cboAuthor, and the author doesn't exist, I need to press enter and have a form called frmAddAuthorFly open. After I have added the author, and close the form, I need both cboAuthor and lstAuthor to be updated with the new author, and also the author just added, to be selected in lstAuthor. And lstBook to update as well. frmAddAuthorFly has only got three fields; authorID, authorName and authorCategory.
I've wasted a fair amount of time on this, so maybe someone can give the solution. Many thanks...
Spent a bit of time on this today, and this is what I have come up with. Seems to work ok, but if anyone sees any glaring problems, feel free to offer an alternative.
In the NotInList event of cboAuthor
Private Sub cboAuthor_NotInList(NewData As String, Response As Integer)
On Error GoTo errline
Dim MsgBoxAnswer As Variant
Response = acDataErrContinue
MsgBoxAnswer = MsgBox("Do you want to add a new author?", vbYesNo, "Add New Author")
If msboxanswer = vbNo Then
Me.cboAuthor = Null
DoCmd.GoToControl "cboAuthor"
GoTo exitline
Else
txtHidden = "addOk"
DoCmd.OpenForm ("frmAddAuthorFly")
DoCmd.GoToRecord , , acNewRec
Forms![frmaddauthorfly]![AuthorName] = NewData
Me.cboAuthor = Null
DoCmd.GoToControl "authorcategory"
End If
exitline:
Exit Sub
errline:
Exit Sub
'Select Case Err.Number
End Sub
I've added a cmdButton to frmAddAuthorFly and included the following code:
Private Sub cmdClose_Click()
On Error GoTo errline
If Forms![frmmain]![txtHidden] = "addok" Then
Forms![frmmain]![cboAuthor].Requery
Forms![frmmain]![LstAuthor].Requery
Forms![frmmain]![LstAuthor] = Me.AuthorID
Forms![frmmain]![txtHidden] = "AddDone"
DoCmd.Close acForm, "frmAddAuthorFly"
Forms![frmmain]![cboAuthor].Requery
Forms![frmmain]![LstAuthor].Requery
Forms![frmmain].[LstAuthor].SetFocus
Else
MsgBox "txt hidden is not addok"
DoCmd.Close acForm, "frmaddauthorfly"
End If
errline:
Exit Sub
End Sub
One thing that I would have like to do, is after I set the focus on the new author just added record, in the listbox, is have it clicked. Not just highlighted, but I guess I can click it ...

Filter in OpenOffice Calc

Scenario:
I have a spreadsheet with info from a giveaway campaign in which I get paid per new Twitter follow my client receives through my campaign. Unfortunately the application I use does not track new followers vs existing ones because they offer an entry for new and existing followers for the "Follow on Twitter for 1 Entry". Because I also offer other means to gain entries I need to export the data and filter the results to show only those who've gained an entry on the Twitter Follow and then filter out those who are new vs existing by means of a separate application.
Problem:
There should be a separate column for each data type; name,email,action, etc. The action column is where I would expect to find the "Follow On Twitter" but the file is very disorganized and the action can be found in many different columns. Therefore I need a way to show only the rows in which there is a field with "Follow on Twitter". I am at a loss to try and figure out how to do this.
The following macro will search for "Follow On Twitter" in each cell. For each row, if a match is found, the row will be shown, else it will be hidden. You will have to adjust the macro to match your sheet's total number of rows/columns.
Sub Dummy()
GlobalScope.BasicLibraries.LoadLibrary("Tools")
Dim ActiveSheet As Object
ActiveSheet = ThisComponent.CurrentController.ActiveSheet
Dim r,c As Integer
For r = 0 To 25
Dim found As Boolean
found = False
For c = 0 to 10
Dim cell As Object
cell = ActiveSheet.getCellByPosition(c, r)
If cell.String = "Follow On Twitter" Then
found = True
Exit For
End If
Next c
Dim row As Object
row = ActiveSheet.getRows.getByIndex(r)
row.IsVisible = found
Next r
MsgBox "Done"
End Sub

Calculated control displays the total number of records that appear in the subform

My assignment is to create a calculated control that displays to total number of Members in the subform. How can I accomplish this when there is no definitive field that I can use in the expression. There are only three fields in the subform: First Name, Last Name, and Phone. If I do something like this =[frmPlanMemberSubform].[Form]![FirstName] that only calculate and displays the first name of the member in the subform. Actually there are only two names in the subform. Theoretically I suppose to get back a count of 2. But I can't figure out how to do it with the existing fields in the subform. Any Access experts out there? Please help. Here is what the database looks like in form view.
As you can see there is nothing in the Total Members control box.
Follow these steps:
1) In the code of the master form insert a function similar to this:
Private Function NumRecords()
Dim rec As Recordset
On Error GoTo lbErr
Set rec = Me!<subform-name>.Form.RecordsetClone
rec.MoveLast
NumRecords = rec.RecordCount
lbExit:
Exit Function
lbErr:
MsgBox Error, vbExclamation
Resume lbExit
End Function
2) In the field to display the number of records insert the following string in the value property:
=NumRecords()
3) Create the Form_Current trigger as follows:
Private Sub Form_Current()
Me!<fieldname>.Requery
End Sub
enter image description here

sorting across sheets in excel

I don't know if this is possible or not.
I have a workbook that has two sheets, "input" and "output"
user1 fills in the "input sheet"
Column A = name
Column B = Age
Column C = Location
Column D = Hight
..
..
Then on the "output" sheet Column A is set to copy the value from Column A on the "input" sheet and User2 fills in more details using the values that user1 has entered
Column B = eye colour
Column C = hair colour
Column D = number of fingers
..
..
So I hope you get the idea, User1 enters some details, and then User2 does some work with that and enters more details in the "output sheet. With Column A being the "index" value that links the two together.
My issue is that if User2 enters there details, and then goes back to the "input" sheet and preforms a sort, the values in the "output" sheet will no longer match, as while Column A will have changes to reflect the sort operation the rest will stay the same.
Is it possible to link rows between sheets, or to create a sort code that will run across both sheets and keep them consistence.
This does not have to work for ad-hoc searches that the user tries, I just want to put a button on the "input" sheet, for example to "sort by name", "sort by Location" etc
Regards
Aaron
If you're ok with having pre-set sorts, one solution is to mirror both values from sheet A and sheet B to sheet C, and then just sort that, and re-populate the values in sheet A and B with the new, sorted, results.
I.e.
Sheet1 | Sheet 2 | Sheet 3 (Hidden and named)
| |
Name Age etc, | Eye Colour Hair colour etc. | =Sheet1!A1 ... =Sheet2!A1
Then your sort button would call a sub something like:
Dim rngSortRange As Range, rngStartCell As Range, rngEndCell As Range
Set rngStartCell = Worksheets("Sheet_3_Name_Goes_Here").Range("A1")
Set rngEndCell = Worksheets("Sheet_3_Name_Goes_Here").Range( _
rngStartCell.End(xlToRight).Column, _
rngStartCell.End(xlDown).Row)
Set rngSortRange = Worksheets("Sheet_3_Name_Goes_Here").Range(rngStartCell, rngEndCell)
rngSortRange.Sort Key1:=<Column Number Here>, Order1:=xlAscending, Header:=xlYes
rngSortRange.Range(rngStartCell, _
Worksheets("Sheet_3_Name_Goes_Here").Range( _
Worksheets("Sheet 1").Range("A1").End(xlToRight).Column, _
rngEndCell.Row _
) _
).Copy
Worksheets("Sheet 1").Paste
rngSortRange.Range(Worksheets("Sheet_3_Name_Goes_Here").Range(
rngStartCell.Column + Worksheets("Sheet 1").Range("A1").End(xlToRight).Column, _
rngStartCell.Row _
), _
rngEndCell _
).Copy
Worksheets("Sheet 2").Paste
That might need some work (e.g. you might need to reset sheet3 afterwards, you might need to pastevalues rather than just paste, else you'll end up pasting self-referencing formulas), but the basic idea should work.

Resources