Mix text and data to make a paragraph in Access - vba

I am working on a MS Access 2010 database where users proceed through several form pages of data entry and then are given the option to print a narrative report of the findings.
Some pages of the report have thing such as a text box that reads "Number of Widget A Sold:" and then next to it a Field for WidgetASold which is fine for that section. However, for one of the reports I would like this information integrated into a paragraph of text such as:-
In this fiscal year we sold WidgetASold units of Widget A and WidgetBSold units of Widget B.
I have tried using VBA:-
Dim a As String
Dim b As String
Dim c As String
Dim d As String
Dim WidgetASold As String
Dim WidgetBSold As String
a = "In this fiscal year we sold "
b = " units of Widget A and "
c = " units of Widget B"
d = a & WidgetASold & b & WidgetBSold & c
Which I honestly don't even know if it is a good way to go about things. I have also considered having the text in its own table but I still wouldn't know how to get five fields to line up together in one paragraph.
Basically what I am looking for is the access equivalent of excel's
=CONCATENATE("Some text ",B2," more text ",B12," last text.")
Thank you in advance for your assistance.

To do this, you use an expression as control source of a text box:
= "In this fiscal year we sold " & [WidgetASold] & " units of Widget A and " & [WidgetBSold] & " units of Widget B."
This assumes that WidgetASold and WidgetBSold are included in the record source of the report.
You could do it with VBA in the On Format event of the section, but there is really no reason to do so.

Related

Returning a quick statistical info for a cell as a comment

I have a long list of data on an excel table. This data includes detail information of each order in several rows. There is a column shows the status of each row. Also, I have a dashboard which just lists out the order names. I want the users to be able to see a short statistical info of each book as a comment or when they mouse over the cell, if possible or as a cell data. The info could be something like underneath sample in 3 or 4 row. (The number of items is the count of rows with the same status)
5 issued item
3 shortage items
2 Done items
X other
If you just give me the general idea it would be great.
I think I have to use a collection procedure, something like "scripting dictionary" but I have no experience using them. I know how to do that by putting a case statement after if clause inside a loop, but I am looking for a smarter way. you can find some pictures and a sample data below: sample pictures
For the record, I came to this answer from one of friends in MrExcel froum. Hope you find it usefull.
The just difference is, I was looking for a momentum reply just for an active cell, but this code, provide all the information for all the order names as a comment. but it is very easy to adjust!
Sub UpdateComments()
Dim c As Variant, strComment As String
Dim intISSUED As Integer, intSHORTAGE As Integer
Dim tblDATA As ListObject, tblDASH As ListObject
Set tblDATA = Application.Range("TBL.data").ListObject 'adjust Table Name
Set tblDASH = Application.Range("TBL.dash").ListObject 'adjust Table Name
For Each c In tblDASH.ListColumns("W/B").DataBodyRange
strComment = ""
intISSUED = Application.CountIfs(tblDATA.ListColumns("Work Book").DataBodyRange, c, tblDATA.ListColumns("Stage").DataBodyRange, "Issued")
strComment = strComment & Chr(10) & "Issued: " & intISSUED
intSHORTAGE = Application.CountIfs(tblDATA.ListColumns("Work Book").DataBodyRange, c,tblDATA.ListColumns("Stage").DataBodyRange, "Shortage")
strComment = strComment & Chr(10) & "Shortage: " & intSHORTAGE
' ADDITIONAL 'STAGES' HERE
' OR put 'stages' in array to condense code
With Sheets(tblDASH.Parent.Name).Range(c.Address)
If .Comment Is Nothing Then
.AddComment
.Comment.Visible = False
End If
.Comment.Text Text:=Mid(strComment, 2)
End With
Next c
End Sub

How to pass "Month" and "Year" Only parameter from datetimepicker to crystal report?

Good morning, i am struggling with this Crystal report problem, i have the formula on my report :
cstr(monthname(month({kwitansi1.tgl_kwitansi})))+" - " +cstr(year({kwitansi1.tgl_kwitansi}),0)
It is working and showing the data that i want, which is like this :
May-2015 $1000
June-2015 $600
July-2015 $250
August-2015 $1500
And i have 2 parameter, "?month1" and "?Month2", when i preview it say the field name is not known.
Those parameters is for datetimepicker1 and datetimepicker2.
So basically i want to show, for example:
if i click on datetimepicker1 then fill it with some random date but Month is May-2015 and then i click datetimepicker2 fill it with random date too but Month is August-2015, and then i click "print" button, the crystal report should show those data above that i want.
I am using this on vb.form to pass the parameters to Crystal Report.
objrepdoc = New CRLaporanPendapatanPerbulan
objrepdoc.SetParameterValue("month1", Format(FormCetakLaporanPendapatan.datetimepicker1.Value, "MMMM-YYYY"))
objrepdoc.SetParameterValue("month2", Format(FormCetakLaporanPendapatan.datetimepicker2.Value, "MMMM-YYYY"))
objrepdoc.RecordSelectionFormula = "{kwitansi1.tgl_kwitansi} >= #" & Format(FormCetakLaporanPendapatan.datetimepicker1.Value, "MMMM-YYYY") & "# And {kwitansi1.tgl_kwitansi} <= #" & Format(FormCetakLaporanPendapatan.datetimepicker2.Value, "MMMM-YYYY") & "#"
I know those codes is wrong, :( because if i chose any month, the crystal report show all the data that has been saved on the date (kwitansi1.tgl_kwitansi) field. What i want is the CR is to show only specified data that VB.Form send using datetimepicker1 and datetimepicker2
Since there's no one answer my question, i will answer this for reference of other people that have the same problem.
So, the easy part is actually:
Make 2 parameters, first for the starting parameter and second for the ending parameter, basically we will make an "In between" code.
After that, right click on the print area (everywhere) and click Report> selection formula > Record > The dialog showed up > copy-paste this {tableA.date_table} in {?parameter1} to {?parameter2}
Save them
On the windows form use this:
Make 2 datetimepicker
Copy-paste this on form:
Dim objrepdoc As New ReportDocument
`objrepdoc = New CrystalReport1
objrepdoc.SetParameterValue("parameter1", Format(Form1.DTdate1.Value, "yyyy-MM-dd"))
objrepdoc.SetParameterValue("parameter2", Format(Form1.DTdate2.Value, "yyyy-MM-dd"))
objrepdoc.RecordSelectionFormula = "{tableA.date_table} >= #" & Format(Form1.DTdate1.Value, "yyyy-MM-dd") & "# And {tableA.date_table} <= #" & Format(Form1.DTdate2.Value, "yyyy-MM-dd") & "#"`
NOTE: The datetimepicker may show the date as well , you can modify it so that datetimepicker shows only month and Year.

MS Access multi field search with empty fields or multiple selections from list boxes

can some one kindly help me with MS Access? My problem is similar to the one in the following link:
MS Access multi field search with empty fields
but in my case, each search field is a list box from which we can select multiple things.
In my case, the user of the database application will enter start date and end date (text boxes) which will populate the list boxes (cost center, item number, employee id) from a single database table matching the rows that have effective date falling between start date and end date. After populating the list boxes, the user has the choice to either select multiple cost centers or leave the search field blank, multiple item numbers or blank, multiple employee numbers or blank. After selecting, if the command button display results is pressed, we should be able to get the results which satisfy all these search criteria. For example, if I select cost centers 1301, 1302 and employee no.s 492128, 492690, 492959 and leave the item numbers search field blank, then in the data table, all the entries that match these cost centers and employee no.s (all the search fields are separate columns) which fall between the start date and end date should be displayed.
I am unable to get the logic in VB. Please guide me through.
You'll need to build up an sql statement in vba then run it using a recordset, to get the results back.
Obviously I dont know what the data you'll need to get is, or from the tables you;ll get it from, however the where clause needs to be built as follows:
dim wc as string
wc = wc & iif(lst_costcenter.ItemsSelected.Count = 0, "", " AND " & InClause(lst_costcenter, "tablename.columnname", false))
wc = wc & iif(lst_itemnumber.ItemsSelected.Count = 0, "", " AND " & InClause( ...
Finally when building the sql statement, you'll need to chop of the first "AND" in wc & replace it with "WHERE"
wc = iif(wc <> "", " WHERE " & mid(trim(wc), 5), "")
InClause is a function that you need to add in a module, or in the enquiry form itself:
It uses 3 arguments:
1. The listbox control to build an in clause for,
2. A string comprising tablename-dot-columnname being the table/column to be filtered for the values selected in the listbox, &
3. True/False according to whether the datatype of the column is string (true) or numeric (false)
Public Function InClause(lst as ListBox, tblcol as string, isAlpha as boolean)
Dim si As String
Dim vv As Variant
For Each vv In lstBox.ItemsSelected
If isAlpha Then
si = si & "," & Chr(34) & lstBox.Column(0, vv) & Chr(34)
Else
si = si & "," & lstBox.Column(0, vv)
End If
Next vv
If si <> "" Then
si = "(" & tblcol & " IN (" & mid(si, 2) & "))"
End If
InClause = si
End Function
Hope this helps

EDIFACT How to group, spilt, sort and sum up values from a EDI string into variables in VB.NET

I am new to VB.Net 2008. I have a tricky task to resolve, it is regarding extracting characters (values) from a long string, the extracted values from the text shall be summed up and sorted by keywords, reformatted and saved into a CSV file.
It looks something like this but much longer :
UNH+RAM6957'COMPANY1BY500C10'ZEW+REQEST6957'COMPANY2SL200C20'COMPANY1SL300C10'ZEW
The values are seperated by ' .
As first step I splitted the string to make it readable, I used the function like:
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = p_EDI
aryTextFile = LineOfText.Split("'")
For i = 0 To UBound(aryTextFile)
Console.WriteLine((aryTextFile(i)))
Next i
Now the result looks like:
UNB+UNOA:1+CCP:ZEW+STE:ZEW+100901:1200+2010917283
UNH+M000001+ORDRSP:D:96A:UN:EGT102
BGM+02G::ZEW+NOMRES24364+34
DTM+Z05:0:805
DTM+137:201009011000:203
DTM+Z01:201009090400201009100400:719
RFF+AHI:GSCOMPANY1
NAD+ZSO+CCP::ZEW
NAD+ZSH+GSSTATKRAFT::ZEW
TDT+41G++70
LOC+Z11+:::TTF
LIN+1+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBNP::ZEW
LIN+2+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBPA::ZEW
So far so good:
Now I have to extract the date and time from the header:
The line looks like:
**DTM+137**:201009011000:203 should look like
DTM+137:2010.09.01-10:00:203 and store it into a 'incomming_DTM' variable for example
Now the message period would be interresting to know:
The line looke like:
**DTM+Z01**:201009090400201009100400:719 the output should look like:
DTM+Z01 2010.09.09-04:00, 2010.09.10-04:00 and store it into 'period_DTM' variable
As next step I need to parse the next lines until it reaches the KEYWORD LIN
Like:
LIN+1+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBNP::ZEW
NAD+ZSH+COMPANY1RPH N001::ZEW (P Character in word -> SELL QTY:0 KW/h)
LIN+2+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBPA::ZEW
NAD+ZSH+COMPANY1RRH N001::ZEW (R Character in word -> BUY QTY:0 KW/h)
and store the KEYWORDS "QTY" "DTM" "NAD+ZSH" and its following Characters
into variables.
THEN I need to parse until it reaches the next LIN Keyword and store the
keywords there into vaiables again. The goal of this complicated exercise is,
to sum up values of QTY and NAD+ZSH+COMPANY1RVH and NAD+ZSH+COMPANY1RPH
If we have a closer look at the last zwo charaters in COMPANY1RRH and COMPANY1RPH
we see RH and PH, RH means buy and PH means sell.
Maybe it is possible to store BUY or SELL into a Contract vaiable for each LIN?
I need to sum up all sells and buys which where found in the string.
Every LIN marks a time period of one hour, so we have probably 24 series per
string which contains 24 LIN every LIN have a Time period, BUY or SELL keywords
and a Quantity.
Can someone please help me with this task?
As first step, storing the keywords and its follwoing characters into variables would
be a very good start. It might be very good to do that probably until the parser reaches the LIN, then store the found values into a CSV file or Array?, then parse until the next LIN and so on...
I would like to create a CSV file out of the results like: So the CSV should contain
24 records one per every hour per every LIN..
Dim csvData = Now & "," & "TRADED_QTY" & "," & DTM+Z01 & "," & "N" & "," & QTY & "," & "KWH/h" & "," & Contract
Console.WriteLine(csvData)
Creating the CSV File with True Flag -> Append data to CSV.
Dim csvFile As String = "C:\Test.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
Any ideas are highly welcome, I consider this as very complex task
espacial as I am really new to VB.NET.
Thank you in advance!
I see "EDI" in your code. If this is an EDI format, then you should have, or be able to get, some kind of EDI specification. Likely, it will be a fixed-length specification, meaning that "Value X is characters 1 to 9", "Value Y is characters 10 to 11", "Value Z is character 12", etc.
Here is one possible approach to parse out the KEYWORDS as first step:
Dim EDI As Object
EDI = dataReader(0)
'Convert EDI Object into a string and write it to the console.
Dim p_EDI As String = Convert.ToString(EDI)
'Create LineBreaks after every " ' "
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = p_EDI
aryTextFile = LineOfText.Split("'")
'Starting with IF clause to find keywords
For Each line As String In aryTextFile
Console.WriteLine(line)
If line.StartsWith("UNB") Then
Dim foundUNB_Data = p_EDI.IndexOf("UNB")
'Start at that position and extract UNB + 27 characters
Dim UNBData = EDI.Substring(foundUNB_Data, 30)
Console.WriteLine(UNBData)
ElseIf line.StartsWith("LIN") Then
.
.
ElseIf line.StartsWith("QTY") Then
.
.
End If
Next
Any further ideas are highly welcome..
Thank you.

DLookup in Access not running until textBox clicked on in Form

I'm setting 12 TextBox ControlSources in my Form from VBA using the following :
...
Me.Oct.ControlSource = "=DSum('GBPValue', 'MF YTD Actual Income & Adret', 'Month=10 AND Org_Type=[Key]')"
Me.Nov.ControlSource = "=DSum('GBPValue', 'MF YTD Actual Income & Adret', 'Month=11 AND Org_Type=[Key]')"
...
[Key] is the name of a textbox in the form
When the form loads up i get some odd behavior -
all of the summary form text boxes are blank as are all the dlookup text boxes
if i then click on one of the text boxes that has a dlookup control source assigned the summary text boxes for the other columns start to populate with 0's and #Num etc. and the dlookup runs and displays the expected numbers
once i've clicked on all the dlookup fields the summary numbers calc properly.
In the final version of this the query will be re-written after user clicks from the VBA so ... is this a sensible way to get the form to re-query the DB and, if so, how can i make the DLookups run/display automatically so that everything displays immediately on form load?
You are probably looking for Recalc (Me.Recalc). However, I suggest you use a recordset, rather than DlookUp, and the Current event for the form:
Dim rs As DAO.Recordset 'Needs MS DAO 3.x library
Dim db As Database
Dim strSQL As String
Set db = CurrentDb()
'Guessing that key is a form value
'Note that Month is a reserved word
strSQL = "SELECT [Month], Sum(GBPValue) As SumVal " _
& "FROM [MF YTD Actual Income & Adret] " _
& "WHERE Org_Type= " & Me.[Key]
& " GROUP BY [Month]"
Set rs=db.OpenRecordset(strSQL)
'You can probably use a Do While Loop, consider
'naming the controls, eg, Month10
rs.FindFirst "[Month]=10"
Me.Oct = rs!SumVal
'and so on