Find function in excel: search by keyword - forms

I have a form in which you introduce the product code and it returns its description and price. I would like to add another search criteria to be able to look for the product by keyword, searching in the "description" column. I'm not sure whether the "find" function allows doing this, or if I need to use the "vlookup" function. The problem that I found with "vlookup" is that I would like to be able to keep searching in the column for the rest of the matchs. This is the code that I have working at the moment:
Option Explicit
Dim Llave As Boolean
Private Sub BtnBuscar_Click()
If Not Sheet1.Range("C1:C211").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then
If Llave Then
Cells.FindNext(After:=ActiveCell).Select
Fila.Caption = ActiveCell.Row
Dato1.Caption = ActiveCell.Value
Dato2.Caption = ActiveCell.Offset(0, 1).Value
Dato3.Caption = ActiveCell.Offset(0, 2).Value
Dato4.Caption = ActiveCell.Offset(0, 4).Value
Else
Sheet1.Range("C1:C211").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole).Select
Fila.Caption = Sheet1.Range("C:C").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole).Row
Dato1.Caption = Sheet1.Range("C:C").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole).Value
Dato2.Caption = Sheet1.Range("C:C").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1).Value
Dato3.Caption = Sheet1.Range("C:C").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 2).Value
Dato4.Caption = Sheet1.Range("C:C").Find(Me.DatoBuscado, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 4).Value
Llave = True
End If
Else
Dato1.Caption = " "
Dato2.Caption = " "
Dato3.Caption = " "
Dato4.Caption = " "
Fila.Caption = " "
MsgBox "Dato Inexistente", 64, ""
End If
End Sub
Private Sub Dato1_Click()
End Sub
Private Sub Dato3_Click()
End Sub
Private Sub Fila_Click()
End Sub
Private Sub UserForm_Initialize()
Llave = False
End Sub
So it's a search form (Userform) that I pop up when clicking a button on the worksheet (shee1).
Thanks a lot in advance!
Natalia.

I would suggest using Find in a DO UNTIL loop until the range returned by find is nothing and use that loop to populate a listbox. Then the user can select the match that the want.

Related

Libre Office custom Dialog Table

I am creating a custom Dialog where the user is supposed to select one of multiple possible entries. I use a List Box to list the possible entries to be selected from.
There are multiple variables for each row, therefore I would like to use a table to properly align the entries. Is there a possibility to do so?
What i have:
abcdefg hijkl mnopq
abcd efghijk lmno
What i want:
abcdefg hijkl mnopq
abcd efghilkl mno
Use a fixed-width font for the list box, and pad the strings with spaces.
Sub PaddedListboxItems
oListBox.addItems(Array(
PaddedItem(Array("abcdefg", "hijkl", "mnopq")),
PaddedItem(Array("abcd", "efghijk", "lmno"))), 0)
End Sub
Function PaddedItem(item_strings As Array)
PaddedItem = PadString(item_strings(0), 10) & _
PadString(item_strings(1), 11) & item_strings(2)
End Function
Function PadString(strSource As String, lPadLen As Long)
PadString = strSource & " "
If Len(strSource) < lPadLen Then
PadString = strSource & Space(lPadLen - Len(strSource))
End If
End Function
More ways to pad strings in Basic are at http://www.tek-tips.com/viewthread.cfm?qid=522164, although not all of them work in LibreOffice Basic.
Yes, it is possible.
Create a new dialog and at the bottom, add a label.
Create a new module and add following code:
Option Explicit
Option Base 0
Dim oDialog1 As Object, oDataModel As Object, oListener As Object
Sub OpenDialog()
Dim oGrid As Object, oGridModel As Object, oColumnModel As Object, oCol As Object
Dim oLabel1 As Object, rect(3) As Integer
DialogLibraries.LoadLibrary("Standard")
oDialog1 = CreateUnoDialog(DialogLibraries.Standard.Dialog1)
oGridModel = oDialog1.getModel().createInstance("com.sun.star.awt.grid.UnoControlGridModel")
oLabel1 = oDialog1.getModel().getByName("Label1")
rect(0) = oLabel1.getPropertyValue("PositionX")
rect(1) = 10
rect(2) = oLabel1.getPropertyValue("Width")
rect(3) = oLabel1.getPropertyValue("PositionY") - 2*rect(1)
With oGridModel
.PositionX = rect(0)
.PositionY = rect(1)
.Width = rect(2)
.Height = rect(3)
End With
oColumnModel = oGridModel.ColumnModel
oCol = oColumnModel.createColumn()
oCol.Title = "Column 1"
oColumnModel.addColumn(oCol)
oCol = oColumnModel.createColumn()
oCol.Title = "Column 2"
oColumnModel.addColumn(oCol)
oCol = oColumnModel.createColumn()
oCol.Title = "Column 3"
oColumnModel.addColumn(oCol)
oDialog1.getModel().insertByName("grid", oGridModel)
oGrid = oDialog1.getControl("grid")
oListener = (CreateUnoListener("grid_", "com.sun.star.awt.grid.XGridSelectionListener"))
oGrid.addSelectionListener(oListener)
oDataModel = oGridModel.GridDataModel
oDataModel.addRow("a", Array("abcdefg", "hijkl", "mnopq"))
oDataModel.addRow("b", Array("abcd", "efghijk", "lmno"))
oDialog1.execute()
oDialog1.dispose()
End Sub
To get the values of the selected row, add a listener for the grid_selectionChanged event:
Sub grid_selectionChanged(ev)
Dim oRows() As Object, oLabel1 As Object, sCells(2) As String
oRows = ev.Source.getSelectedRows()
oLabel1 = oDialog1.getModel().getByName("Label1")
sCells(0) = oDataModel.getRowData(oRows(0))(0)
sCells(1) = oDataModel.getRowData(oRows(0))(1)
sCells(2) = oDataModel.getRowData(oRows(0))(2)
oLabel1.setPropertyValue("Label", "Selected values: " + sCells(0) + "," + sCells(1) + "," + sCells(2))
End Sub
If you did all correctly, by running OpenDialog you should get your grid:

simplest Unostructure that supports he getByName

In LibreOffice Basic sub I use a bunch of uno properties in an array. Which is the simplest Unostructure or UnoService that I must "embed" them, in order to use the getByName "function"?
Example:
dim props(1) as new com.sun.star.beans.PropertyValue
props(0).Name = "blahblah1"
props(0).Value = "blahblah1Value"
props(1).Name = "blahblah2"
props(1).Name = 3000
I want to be able to use something like:
b = props.getByName("blahblah2").Value
or something like (assuming I "assigned" them in a structure-like-object called "somestruct") :
b = somestruct.getprops.getByName("blahblah2").Value
As I understand that this can be done by creating a "UnoService" which supports the getByName and then, somehow, assigning these props to this service
Which is the "lightest" such service?
(I mean the service that uses less resources)
Thanks in advance.
Really supporting the interface XNameAccess is not as easy. The services which implement this interface are supposed using this interface for existing named properties, not for own created ones.
But you can use the service EnumerableMap to achieve what you probably want.
Example:
sub testEnumerableMap
serviceEnumerableMap = com.sun.star.container.EnumerableMap
oEnumerableMap = serviceEnumerableMap.create("string", "any")
oEnumerableMap.put("blahblah1", "blahblah1Value")
oEnumerableMap.put("blahblah2", 3000)
oEnumerableMap.put("blahblah3", 1234.67)
msgbox oEnumerableMap.get("blahblah1")
msgbox oEnumerableMap.get("blahblah2")
msgbox oEnumerableMap.get("blahblah3")
'msgbox oEnumerableMap.get("blahblah4") 'will throw error
msgbox oEnumerableMap.containsKey("blahblah2")
msgbox oEnumerableMap.containsValue(3000)
if oEnumerableMap.containsKey("blahblah4") then
msgbox oEnumerableMap.get("blahblah4")
end if
end sub
But starbasic with option Compatible is also able supporting Class programming like VBA does.
Example:
Create a module named myPropertySet. Therein put the following code:
option Compatible
option ClassModule
private aPropertyValues() as com.sun.star.beans.PropertyValue
public sub setProperty(oProp as com.sun.star.beans.PropertyValue)
bUpdated = false
for each oPropPresent in aPropertyValues
if oPropPresent.Name = oProp.Name then
oPropPresent.Value = oProp.Value
bUpdated = true
exit for
end if
next
if not bUpdated then
iIndex = ubound(aPropertyValues) + 1
redim preserve aPropertyValues(iIndex)
aPropertyValues(iIndex) = oProp
end if
end sub
public function getPropertyValue(sName as string) as variant
getPropertyValue = "N/A"
for each oProp in aPropertyValues
if oProp.Name = sName then
getPropertyValue = oProp.Value
exit for
end if
next
end function
Then within a standard module:
sub testClass
oPropertySet = new myPropertySet
dim prop as new com.sun.star.beans.PropertyValue
prop.Name = "blahblah1"
prop.Value = "blahblah1Value"
oPropertySet.setProperty(prop)
prop.Name = "blahblah2"
prop.Value = 3000
oPropertySet.setProperty(prop)
prop.Name = "blahblah3"
prop.Value = 1234.56
oPropertySet.setProperty(prop)
prop.Name = "blahblah2"
prop.Value = 8888
oPropertySet.setProperty(prop)
msgbox oPropertySet.getPropertyValue("blahblah1")
msgbox oPropertySet.getPropertyValue("blahblah2")
msgbox oPropertySet.getPropertyValue("blahblah3")
msgbox oPropertySet.getPropertyValue("blahblah4")
end sub
LibreOffice Basic supports the vb6 Collection type.
Dim coll As New Collection
coll.Add("blahblah1Value", "blahblah1")
coll.Add(3000, "blahblah2")
MsgBox(coll("blahblah1"))
Arrays of property values are the only thing that will work for certain UNO interfaces such as dispatcher calls. If you simply need a better way to deal with arrays of property values, then use a helper function.
Sub DisplayMyPropertyValue
Dim props(0 To 1) As New com.sun.star.beans.PropertyValue
props(0).Name = "blahblah1"
props(0).Value = "blahblah1Value"
props(1).Name = "blahblah2"
props(1).Name = 3000
MsgBox(GetPropertyByName(props, "blahblah1"))
End Sub
Function GetPropertyByName(props As Array, propname As String)
For Each prop In props
If prop.Name = propname Then
GetPropertyByName = prop.Value
Exit Function
End If
Next
GetPropertyByName = ""
End Function
XNameAccess is used for UNO containers such as Calc sheets. Normally these containers are obtained from the UNO interface, not created.
oSheet = ThisComponent.Sheets.getByName("Sheet1")
May UNO objects support the XPropertySet interface. Normally these are also obtained from the UNO interface, not created.
paraStyleName = cellcursor.getPropertyValue("ParaStyleName")
It may be possible to create a new class in Java that implements XPropertySet. However, Basic uses helper functions instead of class methods.
I think the serviceEnumerableMap is the answer (so far). Creating the values and searching them was much faster then creating props in a dynamic array and searching them with a for loop in basic.
(I do not "dare" to use "option Compatible", although I was a big fun of VB6 and VBA, because of the problems in code that maybe arise).
I used this code to test time in a form:
SUB testlala(Event)
TESTPROPS(Event)
' TESTENUM(Event)
MSGBOX "END OF TEST"
END SUB
SUB TESTENUM(Event)
DIM xcounter AS LONG
'b = now()
serviceEnumerableMap = com.sun.star.container.EnumerableMap
oEnumerableMap = serviceEnumerableMap.create("string", "any")
FOR xcounter= 0 TO 10000
oEnumerableMap.put("pr" & FORMAT(xcounter,"0000"), xcounter -10000)
NEXT
'b=now()-b
b = now()
FOR xcounter = 1 TO 5000
lala = Int((9000 * Rnd) +1)
g =oEnumerableMap.get("pr" & FORMAT(lala,"0000"))
'MSGBOX GetValueFromName(props,"pr" & FORMAT(xcounter,"0000"))
NEXT
b=now()-b
MSGBOX b*100000
END SUB
SUB TESTPROPS(Event)
DIM props()
DIM xcounter AS LONG
'b = now()
FOR xcounter= 0 TO 10000
AppendProperty(props,"pr" & FORMAT(xcounter,"0000"), xcounter -10000)
NEXT
'b=now()-b
b = now()
FOR xcounter = 1 TO 5000
lala = Int((9000 * Rnd) +1)
g = GetValueFromName(props,"pr" & FORMAT(lala,"0000"))
'MSGBOX GetValueFromName(props,"pr" & FORMAT(xcounter,"0000"))
NEXT
b=now()-b
MSGBOX b*100000
END SUB
REM FROM Andrew Pitonyak's OpenOffice Macro Information ------------------
Sub AppendToArray(oData(), ByVal x)
Dim iUB As Integer 'The upper bound of the array.
Dim iLB As Integer 'The lower bound of the array.
iUB = UBound(oData()) + 1
iLB = LBound(oData())
ReDim Preserve oData(iLB To iUB)
oData(iUB) = x
End Sub
Function CreateProperty(sName$, oValue) As com.sun.star.beans.PropertyValue
Dim oProperty As New com.sun.star.beans.PropertyValue
oProperty.Name = sName
oProperty.Value = oValue
CreateProperty() = oProperty
End Function
Sub AppendProperty(oProperties(), sName As String, ByVal oValue)
AppendToArray(oProperties(), CreateProperty(sName, oValue))
End Sub

Microsoft Access - Loop through all forms and controls on each form

Okay so when I press a specific button I want to loop through all forms, then find every control in each form with the tag 'TESTING'. If the tag = 'TESTING' then I want to change the caption of the object to 'abc123'.
The only objects with the tag 'TESTING' will be labels, so they will have the caption property.
So far I have this as the function:
Public Function changelabel()
On Error Resume Next
Dim obj As AccessObject, dbs As Object
Dim ctrl as Control
Set dbs = Application.CurrentProject
For Each obj In dbs.AllForms
DoCmd.OpenForm obj.Name, acDesign
For Each ctrl In Me.Controls
If ctrl.Tag = "TESTING" Then
ctrl.Caption = "abc123"
End If
Next ctrl
Next obj
End Function
Then this as the button code:
Public Sub TestButton_Click()
Call changelabel
End Sub
So it executes the first for loop and opens all the forms in design view correctly. The problem lies with the second for loop. None of the label captions that have the tag property as 'TESTING' are changed to 'abc123'.
So what do I need to change to get the second for loop to work?
Public Sub GetForms()
Dim oForm As Form
Dim nItem As Long
Dim bIsLoaded As Boolean
For nItem = 0 To CurrentProject.AllForms.Count - 1
bIsLoaded = CurrentProject.AllForms(nItem).IsLoaded
If Not bIsLoaded Then
On Error Resume Next
DoCmd.OpenForm CurrentProject.AllForms(nItem).NAME, acDesign
End If
Set oForm = Forms(CurrentProject.AllForms(nItem).NAME)
GetControls oForm
If Not bIsLoaded Then
On Error Resume Next
DoCmd.Close acForm, oForm.NAME
End If
Next
End Sub
Sub GetControls(ByVal oForm As Form)
Dim oCtrl As Control
Dim cCtrlType, cCtrlCaption As String
For Each oCtrl In oForm.Controls
If oCtrl.ControlType = acSubform Then Call GetControls(oCtrl.Form)
Select Case oCtrl.ControlType
Case acLabel: cCtrlType = "label": cCtrlCaption = oCtrl.Caption
Case acCommandButton: cCtrlType = "button": cCtrlCaption = oCtrl.Caption
Case acTextBox: cCtrlType = "textbox": cCtrlCaption = oCtrl.Properties("DataSheetCaption")
Case Else: cCtrlType = ""
End Select
If cCtrlType <> "" Then
Debug.Print oForm.NAME
Debug.Print oCtrl.NAME
Debug.Print cCtrlType
Debug.Print cCtrlCaption
End If
Next
End Sub
Something like this
Public Function changelabel()
Dim f As Form
Dim i As Integer
Dim c As Control
For i = 0 To CurrentProject.AllForms.Count - 1
If Not CurrentProject.AllForms(i).IsLoaded Then
DoCmd.OpenForm CurrentProject.AllForms(i).Name, acDesign
End If
Set f = Forms(i)
For Each c In f.Controls
If c.Tag = "TESTING" Then
c.Caption = "TESTING"
End If
Next c
Next i
End Function
You'll need to add a bit of house-keeping to set the objects used to nothing etc..

excel 2010: based on a radio button selection save user from date to ain a different worksheet

I have a excel form which works and saves data to just one worksheet. I like to be able to put a radio button and based on that selection i like to save to a diffent work sheet.
example:
if radio button 1 is selected save to sheet1
if radio button 2 is selected save to sheet2
if radio button 3 is selected save to sheet3
same form used to save on different worksheet.
the code im working with.
Private Sub btn_append_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Assessment")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a part number
If Trim(Me.txt_roomNumber.Value) = "" Then
Me.txt_roomNumber.SetFocus
MsgBox "Please enter a Room Number"
Exit Sub
End If
'copy the data to the database
'use protect and unprotect lines,
' with your password
' if worksheet is protected
With ws
' .Unprotect Password:="password"
.Cells(iRow, 1).Value = Me.txt_roomNumber.Value
.Cells(iRow, 2).Value = Me.txt_roomName.Value
.Cells(iRow, 3).Value = Me.txt_department.Value
.Cells(iRow, 4).Value = Me.txt_contact.Value
.Cells(iRow, 5).Value = Me.txt_altContact.Value
.Cells(iRow, 6).Value = Me.cbx_devices.Value
.Cells(iRow, 7).Value = Me.cbx_wallWow.Value
.Cells(iRow, 8).Value = Me.txt_existingHostName.Value
.Cells(iRow, 10).Value = Me.cbx_relocate.Value
If Me.ckb_powerbar.Value = True Then Cells(iRow, 11).Value = "Y"
If Me.ckb_dataJackPull.Value = True Then Cells(iRow, 12).Value = "P"
.Cells(iRow, 13).Value = Me.txt_existingDataJack.Value
If Me.ckb_hydroPull.Value = True Then Cells(iRow, 14).Value = "P" Else Cells(iRow, 14).Value = "A"
.Cells(iRow, 19).Value = Me.txt_cablePullDesc.Value
.Cells(iRow, 20).Value = Me.txt_hydroPullDesc.Value
.Cells(iRow, 21).Value = Me.Txt_otherDesc.Value
' .Protect Password:="password"
End With
'clear the data
'Me.txt_roomNumber.Value = ""
'Me.txt_roomName.Value = ""
'Me.txt_department.Value = ""
'Me.txt_contact.Value = ""
'Me.txt_altContact.Value = ""
Me.cbx_relocate.Value = ""
Me.txt_existingHostName = ""
Me.txt_altContact.SetFocus
End Sub
Private Sub btn_close_Click()
Unload Me
End Sub
Private Sub ComboBox1_Change()
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
MsgBox "Please use the Close Form button!"
End If
End Sub
The first thing to do is to add the radio-buttons (actually OptionButton) to the form and name them.
Then to check if one of them is selected use code such as:
If optSheet1 Then
'it is checked
ElseIf optSheet2 Then
'the second one is checked
'etc
End If

Dlookup VBA code with 2 criteria

I have an MS Access form with a project_ID field combo box and several other fields. Once the user selects the project_ID field, majority of the subsequent fields on the form are automatically populated. I am trying to add a field on the form that displays information not only based on the project_ID but also a Trans_ID. The catch is that I want the Trans_ID to be a text box on the form, in which the user can simply type in the Trans_ID and in another text box, the Error_DTL_1 field is displayed. This is the VBA code that I have generated so far:
Private Sub cboProjectID_Change()
Dim VarComboKey As Integer
Dim VarObjective As Variant
Dim VarStartDate As Variant
Dim VarEndDate As Variant
Dim VarRiskCategory As Variant
Dim VarTarDatSet As Variant
Dim VarErrorCount As Variant
Dim VarErrorCode As Variant
Dim VarErrorDTL As Variant
VarComboKey = Me.cboProjectID.Value
VarObjective = DLookup("[Objective]", "[Project_HDR_T]", "[Project_ID]= " & VarComboKey)
Me.txtObjective = VarObjective
VarStartDate = DLookup("[Start_Date]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtStartDate = VarStartDate
VarEndDate = DLookup("[End_Date]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtEndDate = VarEndDate
VarRiskCategory = DLookup("[Risk_Category]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtRiskCategory = VarRiskCategory
VartxtTarDatSet = DLookup("[Targeted_Dataset]", "[Project_Targeted_Dataset]", "[Project_ID] = " & VarComboKey)
Me.txtTarDatSet = VartxtTarDatSet
VarErrorCount = DLookup("[Count_Error_Codes]", "[Project_Error_Final]", "[project_ID] = " & VarComboKey)
Me.txtErrorCount = VarErrorCount
VarErrorCode = DLookup("[ErrorCode]", "[Project_Error_Final]", "[project_ID] = " & VarComboKey)
Me.txtErrorCode = VarErrorCode
VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey And "[Trans_ID] = forms![Quality Risk Assessment]!me.stTransID")
Me.txtErrorDTL = VarErrorDTL
End Sub
The two lines before the "End Sub" are my attempt at attacking this code. But every time i make a selection in the Project_ID combo box on the form, i get an error "Run time Error 13, Type Mismatch".
Can anyone help?
In the line...
VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey And "[Trans_ID] = forms![Quality Risk Assessment]!me.stTransID")
...the "And" is outside the quotes, and the second clause seems to mix both the Forms! and me. ways of referencing. Try...
VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey & " And [Trans_ID] = forms![Quality Risk Assessment]!stTransID.Value")
...and see if it works better. Alternatively, you could try...
VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey & " And [Trans_ID] = " & me.stTransID.Value)
A recordset:
Dim rs As DAO.Recordset
sSQL = "SELECT p.Objective, p.Start_Date, p.End_Date FROM Project_HDR_T p " _
& "WHERE p.Project_ID = " & VarComboKey
Set rs = CurrentDb.OpenRecordset(sSQL)
If rs.EOF Then
MsgBox "oops"
Else
VarObjective = rs!Objective
VarStartDate = rs!Start_Date
VarEndDate = rs!End_Date
End If
And given that all your tables contain Project_ID, it should be possible to create a query that includes all the tables, furthermore, the query coud be saved and referenced with a parameter in code.
See also:
What is a Recordset in VBA? ... what purpose does it serve?
Recordset Object