Multiply two text box values and show sum in third text box - vba

I need to multiply the values of two text boxes and display the sum in a third text box in Word.
I have tried every variation of code I can think of.
When entering data in the first two text boxes, no error is generated but no answer appears in the third text box.
I am trying to multiply the results entered into Word text boxes (Legacy Forms, Text Form Fields) bookmarked "Text61" and "Amount247", showing the results in the same type of text box, bookmarked "Text71".
Sub MultiplyTotal()
Dim ff As String
ff = ActiveDocument.FormFields("Text61").Result
ff = ActiveDocument.FormFields("Amount247").Result
ff = ActiveDocument.FormFields("Text71").Result = ("Text61") * ("Amount247")
End Sub

The code in the question is on the right track for performing the calculation, it just needs to use the variable(s) for capturing the results and performing the calculation a bit differently.
One variable is required for each item to be included in the calculation.
Since calculations are done with numbers, it's also helpful to force-convert the text (String) to a numerical value (the Val function), although if the user is careful it's not strictly necessary in VBA - but a good habit.
Sub CalculateFF()
Dim ff1 As String, ff2 As String
ff1 = ActiveDocument.FormFields("Text61").Result
ff2 = ActiveDocument.FormFields("Amount247").Result
ActiveDocument.FormFields("Text71").Result = Val(ff1) * Val(ff2)
End Sub
Note that it's not strictly necessary to use code to perform simple calculations in Word documents containing form fields, where forms protection is activated. A calculation type of form field can be used that executes a calculation without the need of code. If that approach is of interest, ask in an end-user venue such as Super User.

Related

cannot get value from a cell in libreoffice 6.4.3.2 basic

I am new to libreoffice basic, i have experience with VBA but this libreoffice is different.
I just want to get cell value but it always return zero value to me while the actuall cell can be text or number.
Here is a partial of my simple code.
Sub test_moved()
Dim Doc As Object
'worksheet
Dim sh_village As Object
Dim sh_cbc As Object
sh_village = ThisComponent.CurrentController.getActiveSheet()
'sh_village = Doc.Sheets.getByName("VillageFinal")
'sh_village = Doc.Sheets(1)
Msgbox(sh_village.getCellrangeByName("B2").getValue())
Msgbox(sh_village.getCellrangeByName("B2").Value)
Msgbox(sh_village.getCellByPosition(1,1).Value)
msgbox("The process is completed.")
End Sub
Do we need to do prior task before start coding?
The code works correctly for numeric values. However, for strings, including strings that look like a number, it will display 0 because there is no numeric value.
What you probably want instead is:
MsgBox(sh_village.getCellRangeByName("B2").getString())
Also check out Format -> Cells -> Number to see how the data is displayed in the cell. And be on the lookout for a single quote at the front of the value in the formula bar (for example '42), because that means it is a string. Delete the quote to make it a number.
i have experience with VBA but this libreoffice is different.
Yes, LibreOffice Basic is a different language from VBA and the LibreOffice API is very different from the MS Office API. Knowing that will help you use it more effectively. If possible, avoid Option Compatible, because it won't fix most problems and will only muddy the waters.

convert text to single type

Dim fontsize As Single = CSng(SynopsisTSCmbFontSize.Text)
rtbSynopsis.Font = New Font(SynopsisTSCmbFonts.Text, fontsize)
to change the fontsize to the value selected in a combo box, the value has to be of the Single type.
the combobox is populated with numbers entered at the design mode, ranging from 7-78. I know that these are entered as strings.
the error is :
I have tried a number of things to convert the text (which are numbers, no letters) from the combobox to single to no avail. try parse did not work, trimming did not work, first convert to INT or DBL, then to SNG did not work.
What is the correct syntax here?
I would have thought that it was pretty standard stuff to change the fontsize.
I found a solution : instead of populating the combobox at design time, I populated it at runtime where I had full control over the type.
Dim i As Single
For i = 5 To 70
SynopsisTSCmbFontSize.Items.Add(i)
TreatmentTSCmbFontSize.Items.Add(i)
Next
once the comboboxes are correctly populated, I can run the rest of the code with no errors
thank you all for your time!

Formatting Unbound Text Box with Value from ComboBox

Novice / Intermediate Access User.
I have a form in MS Access (O365 ProPlus) which has a ComboBox based on six column query.
AfterUpdate, I want to pull the Value from column of the ComboBox and populate it in an unbound text box. However, the formatting needs to be Currency and it's not carrying over correctly from setting the Currency formatting in the Form Properties Field for the Textbox.
I have tried formatting in the Control Source property when pulling the ComboBox column values that way which had limited success. It displayed the Currency format but when I try to use the value in the textbox later to be used in a calculated (Sum) total value field elsewhere on the form, it is only recognized as text.
The TotalValue Textbox only concatenates the textbox(es) with currency dollar signs.
Combobox1_AfterUpdate: ()
Textbox1 = Combobox1.Column (2)
Textbox2 = Combobox1.Column (3)
Textbox3 = Combobox1.Column (4)
TotalValueTextbox = Textbox1 + Textbox2 + Textbox3
Expected results are one number adding up numerical values of the aforementioned text boxes. Instead I get number1number2number3 as if I am concatenating text strings.
Currency format (if it works in preceding text boxes) comes with the dollar sign but decimals don't carry and it concatenates the values in lieu of adding them.
I even tried adding a tertiary test textbox and made its Control Source value equal to 12 times (arbitrary value) of one of the Textboxes and it multiplied correctly, but when multiple text boxes are involved using sum calculation as listed above it didn't work.
Problem is, that a combobox always returns text. If you feed it with numbers or currency, these will formatted using your default settings.
So, add some extra columns to hold your amounts with no currency formatting but forced to text using Str. In your source query of the combobox, add three columns:
Column5: Str([Amount1]
Column6: Str([Amount2]
Column7: Str([Amount3]
Then use convert the values to numbers with Val:
TotalValueTextbox = Val(Combobox1.Column(5)) + Val(Combobox1.Column(6)) +Val(Combobox1.Column(7))
Finally, specify the Format property of TotalValueTextbox as Currency and, in Combobox1, set the column width of the extra columns to 0 (zero).
Using Format() function with Currency parameter results in a string with a $ sign character. Plus (+) character is a concatenation operator left over from old BASIC as well as arithmetic operator. Concatenation will have priority in some situations, as you encountered with textboxes on form.
Instead of formatting data on form, put $ in a label next to textbox.
Otherwise, calculate with direct reference to combobox columns.
= Combobox1.Column(2) + Combobox1.Column(3) + Combobox1.Column(4)

VBA/EXCEL Dynamic Named Range That Includes Both Text and Numbers

Information
I have a column of about 300 part numbers that is constantly expanding. These part numbers can be only numbers, only letters, or a combination of both. I'm using dynamic named ranges with the part numbers to fill combobox lists. When the user types in the part number in the combobox, if we've done that part before it will autofill as they keep typing. I've recently ran into a problem with this however with a recent group of parts that was added.The part number is just a six digit number, and are the only part part numbers that solely consist of numbers, every other one has letters, or if its just numbers there are hyphens in the part number. The combobox I'm filling with this named range does show these numerical part numbers in its list, but does not autofill them when the user types and does not autofill the other information associated with the part number in other textboxes when the part number is done being typed in.
Question
Can anyone help me understand why it isn't autofilling the numerical value but it fills every other value?
Code
Here is the code I'm using to fill the combobox list and the dynamic range formula. Let me know if you need anything else to help you give an answer.
=OFFSET('Part List'!$A$1,0,0,COUNTA('Part List'!$A:$A),1)
comboxPartNumber.List = Range("Part_Number").Value
List of Sample Parts
X-600-ASSY-SM
LO-5093-020-023
LO-5093-020-025
AB-1541754
764761
766415
I cannot add a comment, sice I am 2 points short :(, so I am forced to post this as a solution:
Try to make all the numbers strings.
Dim R As Range
For Each R In Range("Part_Number").Cells
If IsNumeric(R.FormulaLocal) Then R.FormulaLocal = "'" & R.FormulaLocal
Next
Let me know if it worked.

ListBox or Combobox ADODB imported Decimal items invisible in the list

I have encountered this problem several times already and have been able to work around it till now. Also the almighty search engines didn't help me.
The problem is that when I have populated a listbox or combobox from a ADODB recordset all Decimal data elements are not visible in the box, for example with the following (conn is a ADODB connection):
Private Sub GetFilteredRecords()
Dim strSQL As String
Dim arr As Variant
'create the SQL
strSQL = "SELECT * FROM vwStandard_Fee2"
'execute the SQL and fill the rs ( rsFiltered )
Set rsFiltered = conn.Execute(strSQL)
'Apply recordset to the listbox on the form
If Not (rsFiltered.EOF = True And rsFiltered.BOF = True) Then
arr = rsFiltered.GetRows()
With lbDeeper
.ColumnCount = rsFiltered.Fields.Count
.List = TransposeArray(arr)
End With
With cbDeeper
.ColumnCount = rsFiltered.Fields.Count
.List = TransposeArray(arr)
End With
End If
End Sub
Above contains 6 columns of Ids (all show Type = Variant/Decimal), of which the containing values are all not "shown" for some strange reason. Only the String and Date columns are shown normally, the Decimals are there but empty!
Here some snippets:
Now in case of a combo box I can get one column's value shown if their column the BoundColumn when I select that listitem, but only in the value fo the combobox (so still not in the list).
My initial workaround was to convert them into String values before adding to the Listbox/Combobox, in this case however I want to directly link the query result to the Box.List without looking at the details. And thus I am looking for a solution in stead of a work around.
In short: my numerical field items are invisible BY DEFAULT for some strange reason. Workaround was to make the items String values. I am now looking for a solution for this bug/problem instead:
What is causing this?
How to solve it?
So all string data is appearing? And,only numerics don't appear?
Then you may want to convert your numerics to strings and pass it to your list, combo boxes.
Which you have already done I noticed.
Now for any reason if your max number of rows and length of array/recorders row count doesn't match it could also cause an issue. However it seems your setting rows of combobox using recordset row count. Instead of using an array can you try to iterate over the recordset to populate the combobox? yes this is not performance friendly, buy guess what we need it to work without bugs before optimizing. ;-)
Have you bound your combobox to the recordset? Can you confirm if your array is single dimension and it has data to feed to the box?
You may try to populate the listbox using a saved query in the DB to if the issue still persists.
However, list boxes and combo boxes based on SQL statements are slower than
list boxes and combo boxes based on saved queries.
So can you try the following to set rowsource property? Make sure to test on both number,and test columns. As well as on old combo box and new one.
Rowsource->build query->
sqlview copy to rowsource property box->
delete or don't save that above built query since you already have SQL statement.
Just wanted you to try out possibilities to narrow down the issue.
UPDATING ANSWER WITH MOST POSSIBLE ISSUE AND SOLUTIONS
As per my comments, they mainly given assuming you had issues populating listbox/combobox
I forgot to ask something very very important, have you declared
Option Base 1 to make sure to avoid losing one of the array's column
values if you are dumping 2D array...? because you do not have any
explicit declartion for the array you are using to dump data into the
listbox.......... :)
Make sure your Listbox is enabled to show multi column data.
*So you have three choices, *
Option Base 1
ReDim your array and do looping to fill it and dump it into .list.
Since ReDim array need you to anyway loop through, you may just as well
use the recorset iself to add the data.
You seem to have a dimension issue with the array which is not declared but transposed from recordset and then to listbox/combobox. So your undeclared array is not populating multi-columns properly. That could be the reason it works when you declare array proeprly.......
Infact in your comment you have said so,
When I create an array in my code and populate it in my code (entry by
entry) it will show without any problem – K_B 14 mins ago
OK after going through various possible causes it seems to be the case that:
VBA has no Decimal Variant Type of its own.
VBA can handle Decimal from within a variable declared as Variant (thus becoming a Variant/Decimal)
This normally doesn't stop your program from working, but in Controls like Listbox and Combobox the Type Variant/Decimal is not interpretable and thus wont draw that specific entry.
For example populate a listbox called lbHigher with this:
Private Sub ListBoxProblem()
Dim tempArray(2, 2) As Variant
tempArray(0, 0) = "A"
tempArray(0, 1) = 1
tempArray(0, 2) = 1.1
tempArray(1, 0) = "B"
tempArray(1, 1) = CStr(CDec(5.2))
tempArray(1, 2) = 2.3
tempArray(2, 0) = "C"
tempArray(2, 1) = DateSerial(2012, 12, 13)
tempArray(2, 2) = 100
tempArray(3, 0) = "D"
tempArray(3, 1) = -1
tempArray(3, 2) = CDec(5.2)
lbHigher.ColumnCount = 3
lbHigher.List = tempArray
End Sub
Everything works fine except for the CDec(5.2). The CStr(CDec(5.2)) works fine as well as VBA will first have converted the Decimal to String before the Listbox gets to get it.
So either: Dont let the SQL generate any Decimal output OR convert any Decimal output to Single/Double/String/Integer/Long in VBA before handing it to the Listbox.