calculation in VBA - ms-access

have an access database with a form that has multiple textboxes for production data. I need to do a calculation with a few of the boxes, they are set up as
txtA * txtB * txtC = txtD
I need to take the values from each of the boxes and perform this calculation behind the scenes. So I need the value from txtA * txtB * txtC and display the answer to that calculation in txtD. I keep running into issues because of the number of textboxes on my form it will always pick up the wrong data?? HeLP!
Private Sub btnCalculate_Click()
Dim ctrl As Control
Dim txt As TextBox
For Each ctrl In Form.Controls
If TypeOf ctrl Is TextBox Then
Set txt = ctrl
If txt.Name = "txtD" Then
Set txt = ctrl
ctrl.SetFocus
ctrl.Text = calculate
End If
End If
Next ctrl
End Sub
Public Function calculate()
Dim calc1 As Double
calc1 = txtA.Value * txtB.Value * txtC.Value / 144
End Function
I keep getting this error:
Run-time error '2185':
You can't reference a property or mathod for a control unless the control has the focus.
This is in regards to txtA, txtB, txtC.

Try
txtD = calculate()
Or
Me!txtD = calculate()
If, for some reason, you want to access a control by its name, do it like this
Dim name As String
name = "txtD"
Me(name) = calculate()
Your calculation function must assign the result to the function name. A potential problem is that you are ignoring types. Of which type is the result of the function? It will be typed as Variant if you don't specify a type (and a variant can contain about anything). Better
Public Function calculate() As Double
calculate = CDbl(txtA.Value) * CDbl(txtB.Value) * CDbl(txtC.Value) / 144
End Function
Now, everyone who looks at the function knows what kind of data the textboxes should contain and, more important, what kind of result the function returns.

First off, the line
ctrl.Text = calculate
should be
ctrl.Text = calculateBoardFeet()
Next, the code
calc1 = txtA.Value * txtB.Value * txtC.Value / 144
should be
calculateBoardFeet = txtA.Value * txtB.Value * txtC.Value / 144

Related

microsoft access Field must be blank or have a value that is a specific length

I have a field on a form and I need the user to leave it blank or enter a value that is a specific length (20 characters). Does anyone have code that may solve this need?
I have tried:
(Len([SIM / ENGRV]) = 20) or (isnull([SIM / ENGRV])) or ([SIM / ENGRV]="")
I assume the control (field) name in the form is Text1.
So you can use this code in the before update event .
Of course, the code can be much shorter,
But I think that's the clearest way to understand the logic.
Private Sub Text1_BeforeUpdate(Cancel As Integer)
Dim varTmp As Variant
' first check if [ENGRV] > 0 to avoid devision by zero error
If Not IsNumeric([ENGRV]) And [ENGRV] = 0 Then
Text1.Undo
Cancel = True
Else
' now avoid [SIM] is null error
If Nz([SIM], "") = "" Then
Text1.Undo
Cancel = True
Else
varTmp = [SIM] / [ENGRV]
' now we know that varTmp is somthing and not empty then check the length
If Len(Trim(str(varTmp))) <= 20 Then
Text1.Undo
Cancel = True
End If
End If
End If
End Sub
You can do that at the table level. Set the Validation Rule of the field to:
Len([SIM / ENGRV])=20 Or [SIM / ENGRV] Is Null

Access VBA: set ComboBox height through function

I want to use a function to adjust the height of a ComboBox. This is the simplified code :
Private Sub Form_ComboBox_AfterUpdate()
Adjust_Box (Me.Data_Subject_Categories)
End Sub
Private Function Adjust_Box(ctl)
ctl.Height = 300
End Function
But I get the error:
Run-time error '424': Object required
on this row :
ctl.Height = 300
How can I fix it? thanks?
You are using parentheses where you shouldn't, causing evaluation of the parameter - it passes the value of Me.Data_Subject_Categories, not the object.
Use
Call Adjust_Box(Me.Data_Subject_Categories)
or
Adjust_Box Me.Data_Subject_Categories

Null Error on Button Click

I have an access database that has a number of calculations in it. One the the issues I am having is I have multiple textboxes and access want me to enter data into all of them before it calculates the formula. I keep getting an error when I leave a textbox blank
Run-time error '94':
Invalid use of Null
How do I set it to ignore all the nulls. Here is my code
Public Function calculate() as double
calculate = cdbl(textbox1.value) * cdbl(textbox2.value) * cdbl(textbox3.value) * cdbl(textbox4.value) / 144
End Function
Private Sub btn1_click()
Dim x as double
x = calculate
textbox5.value = x
End Sub
Any help would be aprecciated. Thanks!
In your circumstance, I'd use the NZ method.
calculate = cdbl(nz(textbox1.value,1)) * cdbl(nz(textbox2.value,1)) * cdbl(nz(textbox3.value,1)) * cdbl(nz(textbox4.value,1)) / 144

SSRS code variable resetting on new page

In SSRS 2008 I am trying to maintain a SUM of SUMs on a group using custom Code. The reason is that I have a table of data, grouped and returning SUMs of the data. I have a filter on the group to remove lines where group sums are zero. Everything works except I'm running into problems with the group totals - it should be summing the visible group totals but is instead summing the entire dataset. There's tons of articles about how to work around this, usually using custom code. I've made custom functions and variables to maintain a counter:
Public Dim GroupMedTotal as Integer
Public Dim GrandMedTotal as Integer
Public Function CalcMedTotal(ThisValue as Integer) as Integer
GroupMedTotal = GroupMedTotal + ThisValue
GrandMedTotal = GrandMedTotal + ThisValue
Return ThisValue
End Function
Public Function ReturnMedSubtotal() as Integer
Dim ThisValue as Integer = GroupMedTotal
GroupMedTotal = 0
Return ThisValue
End Function
Basically CalcMedTotal is fed a SUM of a group, and maintains a running total of that sum. Then in the group total line I output ReturnMedSubtotal which is supposed to give me the accumulated total and reset it for the next group. This actually works great, EXCEPT - it is resetting the GroupMedTotal value on each page break. I don't have page breaks explicitly set, it's just the natural break in the SSRS viewer. And if I export the results to Excel everything works and looks correctly.
If I output Code.GroupMedTotal on each group row, I see it count correctly, and then if a group spans multiple pages on the next page GroupMedTotal is reset and begins counting from zero again.
Any help in what's going on or how to work around this? Thanks!
Finally found the solution myself. Here it is, add Shared to the variable declarations:
Public Shared Dim GroupMedTotal as Integer
Public Shared Dim GrandMedTotal as Integer
Just changing the variables to shared won't work. If you set them to shared they'll be DOUBLED when you export to PDF / XLS / etc (because it just kept adding to the existing var). You have to do something like this:
Public Shared Dim grandTotal as Decimal
Public Shared Dim costCenterTotal as Decimal
Public Shared Dim workerTotal as Decimal
Public Shared Function Initialize()
grandTotal = 0
costCenterTotal = 0
workerTotal = 0
End Function
Public Function AddTotal(ByVal b AS Decimal) AS Decimal
grandTotal = grandTotal + b
costCenterTotal = costCenterTotal + b
workerTotal = workerTotal + b
return b
End Function
Public Function GetWorkerTotal()
Dim ret as Decimal = workerTotal
workerTotal = 0
return ret
End Function
Public Function GetCostCenterTotal()
Dim ret as Decimal = costCenterTotal
costCenterTotal = 0
return ret
End Function
Public Function GetGrandTotal()
Dim ret as Decimal = grandTotal
grandTotal= 0
return ret
End Function
I don't know where do you use this. but in your case, if I were you, I just use simple expression to check visibility of SUM
for example I'd use Right Click On Sum Box \ Select Expression \ then use IIF(SUM <> 0, sum. "")
It worked on every where and wont reset, in your case you have a Region and your code will reset in every region so you willface with serios isses if you don't change your way.

How do I keep colors consistent from chart to chart in Reporting Services 2005?

I created a custom color palette for my charts using a technique described on TechNet.
I also have a series of drill-through column charts, where you click on one column and it passes a parameter through to the next chart and so on, giving the appearance of drill-down.
My graphs consist of 3 types of labor, and have three colors on the main chart. When I drill down to the next chart, some of the categories do not have all three types of labor that the main one has. So the first color in the palette is assigned to the series, even though it was the second color on the previous chart. I'd like to avoid this, if possible.
So a data value is green on the first chart (2nd in the color order) and yellow on the next chart (1st in the color order). How do I make the graphs "remember" the total number of series groups that were in the first chart?
This is Reporting Services 2005.
You cannot fix this using custom colour palettes.
What you can do is assign the labour type a colour in the database (using HEX is easiest). Then pass that in in your data set. Then set the color property to you hex value.
Unfortunately this is not possible. I've been looking for this for quite some time...
I was able to solve this because I was using a custom color palette, implemented as a hash table. I basically serialized this information and passed it to a hidden parameter on the subreport and then reinflated the data structure.
It's not perfect, but it works for now.
' Define some globals, including the color palette '
Private colorPalette As String() = _
{"#FFF8A3", "#A9CC8F", "#B2C8D9", "#BEA37A", "#F3AA79", "#B5B5A9", "#E6A5A4", _
"#F8D753", "#5C9746", "#3E75A7", "#7A653E", "#E1662A", "#74796F", "#C4384F", _
"#F0B400", "#1E6C0B", "#00488C", "#332600", "#D84000", "#434C43", "#B30023"}
' color palette pulled from SAP guidelines '
' http://www.sapdesignguild.org/resources/diagram_guidelines/color_palettes.html '
Private count As Integer = 0
Private colorMapping As New System.Collections.Hashtable()
' Create a custom color palette '
Public Function GetColor(ByVal groupingValue As String) As String
If colorMapping.ContainsKey(groupingValue) Then
Return colorMapping(groupingValue)
End If
Dim c As String = colorPalette(count Mod colorPalette.Length)
count = count + 1
colorMapping.Add(groupingValue, c)
Return c
End Function
' In custom actions of the data value, set the results of this '
' function to the mapping parameter in the next report '
Public Function PassColorMapping() As String
If colorMapping.Count = 0 Then
Return Nothing
End If
Try
' convert the hashtable to an array so it can be serialized '
Dim objHash As Object()() = ToJaggedArray(colorMapping)
' serialize the colorMapping variable '
Dim outStream As New System.IO.StringWriter()
Dim s As New System.Xml.Serialization.XmlSerializer(GetType(Object()()))
s.Serialize(outStream, objHash)
' move on to the next report '
Return outStream.ToString()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
I ran into an issue where I couldn't find the equivalent of the onLoad event for the report. Since I wasn't sure where to put this inflate code, I stuck it in the background color of the plot area. Hence I always return "WhiteSmoke". I'll change this if I can find the right place to put it.
' Call this function when the report loads to get the series groups '
' that have already been loaded into the custom color palette '
' Pass in the parameter used to store the color mapping '
Public Function InflateParamMapping(ByVal paramMapping As Parameter) As String
Try
If paramMapping.Value Is Nothing Then
Return "WhiteSmoke"
ElseIf colorMapping.Count = 0 Then
Dim pXmlized As String = paramMapping.Value
' deserialize the mapping parameter '
Dim s As New System.Xml.Serialization.XmlSerializer(GetType(Object()()))
' get the jagged array and convert to hashtable '
Dim objHash As Object()() = DirectCast(s.Deserialize(New System.IO.StringReader(pXmlized)), Object()())
' stick the result in the global colorMapping hashtable '
colorMapping = ToHashTable(objHash)
count = colorMapping.Count
End If
Catch ex As Exception
' MsgBox(ex.Message) '
End Try
Return "WhiteSmoke"
End Function
ToJaggedArray() and ToHashTable() are helper functions because a HashTable is not serializable since they implement an IDictionary. I was in a hurry so I just converted them to an array right quick. Code comes from the Collection Serialization in ASP.NET Web
Services article written by Mark Richman. I converted the code from C# to VB.NET to use in the report.
Public Function ToJaggedArray(ByVal ht As System.Collections.HashTable) As Object()()
Dim oo As Object()() = New Object(ht.Count - 1)() {}
Dim i As Integer = 0
For EAch key As Object in ht.Keys
oo(i) = New Object() {key, ht(key)}
i += 1
Next
Return oo
End Function
Public Function ToHashTable(ByVal oo As Object()()) As System.Collections.HashTable
Dim ht As New System.Collections.HashTable(oo.Length)
For Each pair As Object() In oo
Dim key As Object = pair(0)
Dim value As Object = pair(1)
ht(key) = value
Next
Return ht
End Function
Now in the report itself you need to do a couple things.
Add a reference to System.Xml in Report Properties in both reports.
In the Actions of your parent report, set the Parameter containing your data structure to =Code.PassColorMapping()
In the Plot Area section of your report, put this expression for the background: =Code.InflateParamMapping(Parameters!colorMapping)
And of course, in the Fill for your data Series Style on both charts put this expression: =Code.GetColor(Fields!Type.Value)
You can continue doing this for as many subreports as you want - I currently have 3 levels of drill-through and it works fine.
I solved that extremely easy.
In my parent report I have lets say 12 series fields, each one getting their own color in a chart, on my child report I just keep all series on the chart, for instance going from a column chart to a line chart using drill down, but I control the visibility of them...
So in the child report in Series Properties -> Visibility I just add an expression:
=(Fields!ContentType.Value <> Parameters!ContentType.Value)
This way the report only keeps the visibility of the clicked value and hides all the others and the colors remains the same :)