navigating through table records in Access VBA - ms-access

I have a table with two columns (value1 and value2) the values are sorted from lowest to highest. example:
Value1
20
40
43
90
100
122
Value2
4
5
9
10
15
18
I ask the user to enter an input value and then I calculate the value of CalcFinalValue which can be calculated in one of the following:
if the user input value already exist in value1 field, then return the corresponding value of in field value2. for example if the user input is 100 then CalcFinalValue will be 15
if the user input value does not exist in value1 field, then locate the two values in value1 field that the input value is between them(for example if the input value is 42, the I want to locate 40 and 43 from value1 field). Calculate CalcFinalValue as:
CalcFinalValue=(40*9)+(43*5)/42
in other words the formula will be as:
CalcFinalValue=(LowerValue of the inbetween values *lookup value of the HigherValue of the inbetween values)+(HigherValue of the inbetween values *lookup value of the LowerValue of the inbetween values)/(user input value)
I want to perform this in Access 2007 VBA.
I hope this is clear. Thanks for your help in advance!

Dim rs AS DAO.Recordset
Set rs = CurrentDb.OpenRecordset("TableName", dbOpenTable)
' inp stores the user input value; i counts the number of records that have been accessed
Dim inp, i as Integer
' r2c1 and r2c2 store the data of the second row in case the two-row calculation is needed
Dim r2c1, r2c2 as integer
' Since I mostly use forms for I/O that's what I've used here
' Change this to whatever method you use to get the user input
inp = Forms!FormName.InputTextBoxName.Value
i = 0
rs.MoveFirst
Do While (Not rs.EOF)
i = i + 1
' Check if the user input exists in the table
If (rs.Fields("Value1") = inp) Then
' Again use whatever output method you want
Set Forms!FormName.OutputTextBoxName.Value = rs.Fields("Value1")
End Do
' Otherwise, check if the current value in column 1 is greater than the input
Else If (rs.Fields("Value1") > inp) Then
' If this is true for the first row then the input is less than the lowest number.
' I assume this is out-of-bounds, but use whatever boundary condition you want
If (i = 1) Then
MsgBox("Out of Bounds", vbOkOnly)
Else
' Save the required values from this row
r2c2 = rs.Fields("Value2")
r2c1 = rs.Fields("Value1")
' Goto previous row which and calculate according to your formula
rs.MoveLast
Set Forms!FormName.OutputTextBoxName.Value = (r2c1*r2c2 + rs.Fields("Value1")*rs.Fields("Value2"))/inp
End If
End If
rs.MoveNext
Loop
' If nothing was found, the input was larger than all values in 'Value1'
If (rs.EOF) Then
MsgBox("Out of Bounds", vbOkOnly)
End If
Substitute Value1 and Value2 with whatever column names you use

Related

Is there any way to get alphabetical numbering of rows in ssrs instead of numerical numbering?

What I need (alphabetical numbering of rows-highlighted in bold(serial column)):
I have tried converting the output of rownumber function into string, But nothing seems to work as I don't have any idea.
Please help!
You can do this with a bit of custom code.
Go to the Report Properties, click the "Code" tab and paste the following code into the custom code window.
Public Function GetRowLetter(RowNum As Integer) As String
' stick the RowNum in a variable that we can reduce until it's zero
Dim r As Integer
Dim i As Integer
Dim s As String ' holds result
s = ""
r = RowNum
' we start at the right side so if the rownum is 28 we want to be back AB
' need to get 'B' first
Do While RowNum > 0
r = Int((RowNum - 1) / 26)
i = (RowNum - 1) Mod 26
s = Chr(i + 65) & s
RowNum = r
Loop
GetRowLetter = s
End Function
This will give "A" for 1, "B" for 2 etc, then it will give "AA" for 27, "AB" or 28 etc...
If you want to return lower case letters instead, swap the 65 for 98
In your report set the textbox value expression to
=Code.GetRowLetter(RowNumber("myDataSetName"))
swap out myDataSetName with the name of your dataset or scope you want to apply it to. Remember the dataset and scope names are case sensitive and must be surrounded by quotes ( " )

Multi Select List Boxes with Multiple Columns in Access 2013

I have a listbox set to Multiselect property of Simple.
The listbox is populated by using a table.
There are 4 columns in the listbox
1 3/23/2014 4/5/2014 2014
2 4/6/2014 4/19/2014 2014
3 4/20/2014 5/3/2014 2014
The columns are PayPeriod, StartDate, EndDate, FiscalYear
What I want to be able to do is highlight a chunk of dates and have the first selected StartDate and the last selected EndDate populate two hidden text boxes so I can use them for my queries/reports.
I've tried a couple different ways. Each time what happens is it only uses the last item I have selected in it's calculations.
Dim ItemIndex As Variant
For Each ItemIndex In Me.lstPayPeriods.ItemsSelected
If Me.lstPayPeriods.Selected(ItemIndex) And Me.lstPayPeriods.Selected(ItemIndex - 1) = False Then
Date1.SetFocus
Date1.Text = Me.lstPayPeriods.Column(2, Me.lstPayPeriods.ListIndex)
End If
Next
In this example I tried to have it go through each Item of the listbox. I wanted to check to see if the current row was selected and the row before it wasn't. That way I could determine it was the first item selected in the group of selected items. It would always only use the last item I had selected.
Dim CurrentRow As Integer
Dim FirstDate As Date
For CurrentRow = 0 To Me.lstPayPeriods.ListCount - 1
If Me.lstPayPeriods.Selected(CurrentRow) Then
Date2.SetFocus
Date2.Text = Me.lstPayPeriods.Column(3, Me.lstPayPeriods.ListIndex)
End If
Next CurrentRow
For CurrentRow = 0 To Me.lstPayPeriods.ListCount - 1
If Me.lstPayPeriods.Selected(CurrentRow) And Me.lstPayPeriods.Selected(CurrentRow - 1) = False Then
Date1.SetFocus
Date1.Text = Me.lstPayPeriods.Column(2, Me.lstPayPeriods.ListIndex)
End If
Next CurrentRow
I tried to do something similar with this code. Again, it only uses the last item I have selected.
I am running into a wall figuring out how to accomplish my goal.
I think the issue is in your approach. I'm personally not keen on the approach you're using to determine the earliest start and latest end, though the issue might just be your column numbers: the first column in a listbox is column 0, and the last column (of 4 columns) is column 3. Accordingly in your code above, you're setting Date2 = fiscal year, not enddate.
I would however recommend a different approach to determining (a) the earliest selected StartDate, and (b) the latest selected enddate. You could have a loop for each operation, or your can encapsulate both in a function:
private function GetPayPeriodDate(baseValue as Date, findLater as boolean, colNo as long) as Date
'baseValue is the default date to test against
'findLater tells the function whether to look for < or > the baseValue
'colNo tells the function which column of data to test
Dim vv as variant
For each vv in lstPayPeriods.ItemsSelected
if lstPayPeriods.Selected(vv) then
if findLater then
if lstPayPeriods.Column(colNo, vv) > baseValue then
baseValue = lstPayPeriods.Column(colNo, vv)
end if
else
if lstPayPeriods.Column(colNo, vv) < baseValue then
baseValue = lstPayPeriods.Column(colNo, vv)
end if
end if
end if
next vv
GetPayPeriodDate = baseValue
end function
Then you can set your start and end date textboxes by calling this function:
me.StartDate = GetPayPeriodDate(CDate("31/12/2099"), false, 1)
'since startdate looks for the earliest date, the base date must be in the future
me.EndDate = GetPayPeriodDate(CDate("01/01/1900"), true, 2)
'similarly, looking for the latest date, base date must be in the past

Filtering Data from a specific column

Hello Everyone I am at a dilemma I am trying to find out a way to filter out certain data in a column field I have an idea on how to do this but I do not know the correct syntax to use. First here is the table and here is the code structure I would like to write.
for i=1 to length of column First Match
for j=1 to length of column Second Match
If ((value of the data in column First Match = 15) OR (value of the data in column FirstMatch = 1)) AND
((value of the data in column Second Match = 15) OR (value of the data in column Second Match = 1))
Then
Filter the data and append so the filtered datas are saved for both First Match and Second Match
end if
next
next
I am trying to filter out the data that is a 15 and 1 so that only data that have the values 0,2,3,4,5,6...14 will be shown for instance the information of john and steve will not be shown because both the first and second match fields have a 1 or 15 but the rest of data will be shown my form is a split form setup.
Is my method correct?
First Name Last Name First Match Second Match
James Matheson 0 2
Monroe Labonson 4 3
Barack Obama 2 5
Frederick Douglas 3 4
Steve MCGowan 1 1
John Seals 15 15
Mike Omalley 14 15
Set rs = CurrentDb.OpenRecordset("Table1")
Do While Not rs.EOF
If rs!Fields("First Match") > 1 And rs!Fields("First Match") < 15 And rs!Fields("Second Match") > 1 And rs!Fields("Second Match") < 15 Then
End If
Loop
With a better understanding (I hope) I've reproduced your data in Access and built a query that does what you seem to ask. The best way to see this is to create a new query, not add a table, and go directly to SQL view. Paste the following SQL statement (the one in quotes) in and replace matchFilter with your table name.
In your event code you can create a recordset based on the SQL:
Dim sSQL as string, rs as Recordset
sSQL = "SELECT matchFilter.[First Name], matchFilter.[Last Name], matchFilter.[First Match], matchFilter.[Second Match] " & _
"FROM matchFilter " & _
"WHERE ((([First Match]<>1 And [First Match]<>15 And [Second Match]<>1 And [Second Match]<>15)=True))"
Set rs = CurrentDB.OpenRecordset(sSQL)
' now do what you want
Wrong answer below!
Dim rs as Recordset
Set rs = CurrentDB.OpenRecordset("yourTableName")
Do While Not rs.EOF
If rs!Fields("col1") > 1 AND rs!Fields("col1") < 15 AND rs!Fields("col2") > 1 AND rs!Fields("col2") Then
'do what you have to do with filtered out records
End If
Loop
I have found the solution apparently it was just a misunderstanding because the first time I tried this code I thought it was wrong but it was because my field names did not have spaces in between the first time I wrote them.
Me.Filter = ""
Me.Filter = "[First Nam]<>'Jamie' AND [Last Nam]<>'Cartman'"
Me.FilterOn = True

How to display the maximum value from one column in a listbox, in a textbox on the same form

How can I select the maximum value from a column in a listbox, and display that value in a textbox on the same form? The listbox itself is populated by a query that depends on user inputs, so its values are unknown in advance.
I could sort the listbox by value and select the first value, but it is already sorted by date on another column, for a different purpose. What I want to know is the Date on which that maximimum value occurred in column 2.
The next step is to display or all the values in column 4 which occure before that date as blank or N/A.
You may find the following VBA code helpful. It scans values inside the .Column data for a list box named List0, for example...
2013-04-18 | 123
2013-04-17 | 77
2013-04-16 | 345
2013-04-15 | 34
...finds the date (first column) corresponding to the maximum value in the second column of the list box, and puts that date into a text box named Text3. Note that the CompareNumeric flag controls whether the comparison is string-based ("77" would win), or number-based (345 would win).
Private Sub Command2_Click()
Const DateCol = 0 '' column numbers start with 0
Const MaxCol = 1 '' second column has column index of 1
Const CompareNumeric = True '' convert strings to numbers for finding maximum
Dim RowIdx As Long, MaxItem As Variant, MaxIdx As Long, CurrItem As Variant, NewMaxFound As Boolean
MaxIdx = -1
MaxItem = Null
For RowIdx = 0 To Me.List0.ListCount - 1
CurrItem = Me.List0.Column(MaxCol, RowIdx)
If CompareNumeric Then
CurrItem = Val(CurrItem)
End If
If IsNull(MaxItem) Then
NewMaxFound = True '' first one
Else
NewMaxFound = (CurrItem > MaxItem)
End If
If NewMaxFound Then
MaxItem = CurrItem
MaxIdx = RowIdx
End If
Next
If MaxIdx >= 0 Then
Me.Text3.Value = Me.List0.Column(DateCol, MaxIdx)
End If
End Sub

Excel Macro to concatenate multiple rows from Column B per ID rows in Column A with newlines

This problem is in an Excel .xls file.
Simplest Use Case:
Column A has one row.
Column B has 5 rows.
The 5 rows in Column B need to be merged into one row, delimited by newlines.
I have a huge .xls document where there are a ton of IDs in column A.
There are on average anywhere from 3 to 10 rows that belong to each column A row.
How to know which Column B rows belong to which Column A?
By the positioning of the cells.
One Column A row may have 5 Column B rows to the right of it.
I don't have any VBA experience.
I have looked around for macros and functions but haven't had any luck finding anything that matches this problem.
Edit:
I am now trying to figure out how to get the script to ignore rows that have a one-to-one mapping between column A and column B.
Edit again - 06-20-2012:
Now that I can attach images, here is a screenshot of an image for what I'm trying to get.
The rows for Brian and Mark should be ignored, while Scott and Tim get their values copied over.
Edit:
Unmerging column A, using the code that Andy supplied, and then using this VB script afterwards does the trick:
Sub mergeA()
For i = 2 To Cells(65535, 1).End(xlUp).Row
If IsEmpty(Cells(i, 1)) Then Range(Cells(i - 1, 1), Cells(i, 1)).Merge
Next
End Sub
That VB script puts the cells in column A back together
I didn't make the script, it came from this web page:
http://www.vbforums.com/showthread.php?t=601304
This will transform the data shown on the left to the output on the right:
Option Explicit
Sub Make_Severely_Denormalized()
Const HEADER_ROWS As Long = 1
Const OUTPUT_TO_COLUMN As Long = 3
Const DELIMITER As String = vbNewLine
Dim A_Range As Range
Dim B_Range As Range
Dim A_temp As Range
Dim B_temp As Range
Dim B_Cell As Range
Dim Concat As String
On Error GoTo Whoops
Set A_Range = Range("A1").Offset(HEADER_ROWS)
Do While Not A_Range Is Nothing
Set B_Range = A_Range.Offset(0, 1)
' some helper ranges
If A_Range.Offset(1, 0).Value = "" Then
Set A_temp = Range(A_Range, A_Range.End(xlDown).Offset(-1, 0))
Else
Set A_temp = A_Range.Offset(1, 0)
End If
Set B_temp = Range(B_Range, B_Range.End(xlDown)).Offset(0, -1)
' determine how high "B" is WRT no change in "A"
Set B_Range = Range(B_Range, B_Range.Resize( _
Application.Intersect(A_temp, B_temp, ActiveSheet.UsedRange).Count))
' loop through "B" and build up the string
Concat = ""
For Each B_Cell In B_Range
Concat = Concat & B_Cell.Value & DELIMITER
Next
Concat = Left(Concat, Len(Concat) - Len(DELIMITER))
' do the needful
A_Range.Offset(0, OUTPUT_TO_COLUMN - 1).Value = Concat
' find the next change in "A"
If A_Range.Offset(1, 0).Value = "" Then
Set A_Range = Application.Intersect(A_Range.End(xlDown), ActiveSheet.UsedRange)
Else
Set A_Range = A_Range.Offset(1, 0)
End If
Loop
Exit Sub
Whoops:
MsgBox (Err & " " & Error)
Stop
Resume Next
End Sub