bullet points in Access 2010 Report - vba

I'm working on changing an Access 2010 report. There is a portion of the report that reads in Raw Data from a SharePoint field called "Notes" that has comments for each record. Within the "notes" field, there can be several sentences. I need to find a way to separate those sentences into a bullet point per sentence in my report.
I'm trying to come up with a clever way to do so. I can get the data entry folks to use a symbol of some sort in the raw that signifies the need for a new bullet. This way, in my Report Expression (or perhaps via VBA), I can get it separated... but how?
Any thoughts?

The memo data field in MS Access can be set to Rich Text as a property, so:
UPDATE Table1
SET Table1.AMemo = "<ul><li>" &
IIf(InStr([AMemo],".")>0,
Replace(Mid([AMemo],1,Len([AMemo])-1),".","</li>"),[AMemo]) & "</li></ul>"

In its most rudimentary form you could do something like the following. Is splits the [Notes] text on ". " and creates a separate "point" for each sentence.
Sample Data: [SharePointData]
SlideNumber Notes
----------- ------------------------------------
1 Title slide.
2 Brief overview. Just the highlights.
3 More stuff.
VBA Code:
Option Compare Database
Option Explicit
Public Function SplitNoteText(RawText As Variant) As Variant
Dim rtn As Variant, StringArray() As String, Point As Variant
Const BulletChar = "-"
rtn = Null
If Not IsNull(RawText) Then
rtn = ""
StringArray = Split(RawText, ". ", -1, vbBinaryCompare)
For Each Point In StringArray
If Len(Point) > 0 Then
If Len(rtn) > 0 Then
rtn = rtn & vbCrLf & vbCrLf
End If
rtn = rtn & BulletChar & " " & Point
If Right(Point, 1) <> "." Then
' add back the period that got "consumed" in the Split
rtn = rtn & "."
End If
End If
Next
End If
SplitNoteText = rtn
End Function
Test query:
SELECT SlideNumber, Notes, SplitNoteText(Notes) AS Points FROM SharePointData;
Results:
SlideNumber Notes Points
----------- ------------------------------------ ----------------------
1 Title slide. - Title slide.
2 Brief overview. Just the highlights. - Brief overview.
- Just the highlights.
3 More stuff. - More stuff.

Related

Taking a String and Removing text inbetween brackets

I'm trying to make a simple text converter program for my first Visual Basic program. I've already written this in Python but I'm not sure how to do it in Visual Basic.
I need the program to run through the characters of a string and once it encounters a ( to then remove the bracket and ignore the rest of the text until it encounters a ).
For Example,
"This is a (not so good) sentence",
becomes
"This is a Sentence".
Previously I did this with a for loop what looked at a character in the string, then checked if it was open. If it wasn't it would append the character to an output string to the next character or if it was it would then trigger a Boolean to true what would stop the character being appended. It would then continue to stop the future characters from being appended until it found a close bracket. At that point, it would then make the Boolean false, stop the closed bracket from being appended and move back to appending characters, unless it was another bracket.
Sorry if this description is a bit rough as I'm not the best at describing things and I'm very new to visual basic. Thanks for any help given
You can achieve this by several different methods. Here is one method using Instr. Instr returns the character position (index) of a given string in another string. You can use this to determine the bounds of where to include/exclude the string chunk.
You didn't specify if there could be multiple sections encapsulated in () so I assumed there wouldn't be. However, this is a relatively easy tweak by adding either a Do...Loop or a While... loop in the Function.
Hope it helps:
Option Explicit
Public Function removeBrackets(Source As String, Optional RemoveDoubleSpaces As Boolean = False)
Dim FirstBracket As Long
Dim SecondBracket As Long
FirstBracket = InStr(1, Source, "(")
SecondBracket = InStr(1, Source, ")")
If FirstBracket >= SecondBracket Or FirstBracket = 0 Or SecondBracket = 0 Then Exit Function
removeBrackets = Left$(Source, FirstBracket - 1) & Right$(Source, Len(Source) - SecondBracket)
If RemoveDoubleSpaces Then removeBrackets = Replace$(removeBrackets, " ", " ")
End Function
'Run this
Sub Test()
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good) sentence") ' Example given
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good) sentence", True) ' Example given, slight revision. Remove double spaces
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good sentence") ' missing ending bracket
Debug.Print "The value returned is: " & removeBrackets("This is a not so good) sentence") ' missing starting bracket
Debug.Print "The value returned is: " & removeBrackets("This is a not so good sentence") ' No brackets
End Sub

How do I perform a total calculation using price in a combo box?

I am attempting to make a project on visual studio.
I have the following data in a combo box and I was wondering how I would be able to multiply the price (the CStr value) by the number of days the user selects, showing the total in another text box using a calculate button
{cmbPedigreeDog.Items.Add("African Hairless" & CStr(1.14))
cmbPedigreeDog.Items.Add("Boxer" & CStr(0.86))
cmbPedigreeDog.Items.Add("Chihuahua" & CStr(1.83))
cmbPedigreeDog.Items.Add("Dalmation" & CStr(0.65))
cmbPedigreeDog.Items.Add("Eskimo Dog" & CStr(1.14))
cmbPedigreeDog.Items.Add("Farm Collie" & CStr(0.95))
cmbPedigreeDog.Items.Add("GreyHound" & CStr(1.99))
cmbPedigreeDog.Items.Add("Husky" & CStr(1.85))
cmbPedigreeDog.Items.Add("Irish Setter" & CStr(0.65))
cmbPedigreeDog.Items.Add("Jack Russell Terrier" & CStr(1.77))
cmbPedigreeDog.Items.Add("King Charles Spaniel" & CStr(1.02))
cmbPedigreeDog.Items.Add("Labrador Retreiver" & CStr(1.74))
cmbPedigreeDog.Items.Add("Maltese" & CStr(1.47))
cmbPedigreeDog.Items.Add("Pug" & CStr(1.31))
cmbPedigreeDog.Items.Add("Rottweiler" & CStr(2.17))
cmbPedigreeDog.Items.Add("St Bernard" & CStr(1.63))
cmbPedigreeDog.Items.Add("Tibetan Mastiff" & CStr(1.15))
cmbPedigreeDog.Items.Add("Working Sheep Dog" & CStr(0.75))
cmbPedigreeDog.Items.Add("Yorkshire Terrier" & CStr(0.88))
cmbPedigreeDog.Items.Add("Other" & CStr(1.22))}
Not the best way, it requires that all your strings in combobox are of the same pattern with same quantity of delimiters.
Example:
If you use instead of "Boxer" & CStr(0.86) something like "Boxer|" & CStr(0.86) (added just a | symbol), then you can split this string back like this.
line = cmbPedigreeDog.Value
price = CDbl(Split(line, "|")(1))
And some explanations:
Each line of text is a container of symbols. Each can be splitted to array with some delimiter. So the line price = CDbl(Split(line, "|")(1)) can be also written like this:
Dim someArray()
line = "Boxer|" & CStr(0.86)
someArray = Split(line, "|")
' after splitting you have two items in array one is "Boxer" and another is "0.86" (which is text)
' if you follow the pattern in each of your combobox options the price always will be the second one
' so you may refer to second item in array, which is number 1
Price = CDbl(someArray(1))
UPDATE
Another way, as per request in comment. Use two columns combobox. To fill your combobox you have to do following
1 - Go to you ComboBox's properties and set the "ColumnCount" values to 2 (see here how to do it).
2 - This is up to you - you may use the binding with prices on a worksheet as like in topic I gave a link in p.1 or change each line on your code to this pattern:
With cmbPedigreeDog
.AddItem ("Boxer")
.column(1, cbx.ListCount - 1) = 0.86
.AddItem ("Chihuahua")
.column(1, cbx.ListCount - 1) = 1.83
' and so on
End With
3 - To retrieve the price of selected item use such code
If cmbPedigreeDog.ListIndex >= 0 Then
price = cmbPedigreeDog.List(cbx.ListIndex, 1)
Else
MsgBox "item is not chosen"
End If
UPDATE 1
This answer is for VBA, not for Visual Basic WinForm application. For this try to look for a solution like "Multi Column ComboBox"

Connecting to Access from Excel, then create table from txt file

I am writing VBA code for an Excel workbook. I would like to be able to open a connection with an Access database, and then import a txt file (pipe delimited) and create a new table in the database from this txt file. I have searched everywhere but to no avail. I have only been able to find VBA code that will accomplish this from within Access itself, rather than from Excel. Please help! Thank you
Google "Open access database from excel VBA" and you'll find lots of resources. Here's the general idea though:
Dim db As Access.Application
Public Sub OpenDB()
Set db = New Access.Application
db.OpenCurrentDatabase "C:\My Documents\db2.mdb"
db.Application.Visible = True
End Sub
You can also use a data access technology like ODBC or ADODB. I'd look into those if you're planning more extensive functionality. Good luck!
I had to do this exact same problem. You have a large problem presented in a small question here, but here is my solution to the hardest hurdle. You first parse each line of the text file into an array:
Function ParseLineEntry(LineEntry As String) As Variant
'Take a text file string and parse it into individual elements in an array.
Dim NumFields As Integer, LastFieldStart As Integer
Dim LineFieldArray() As Variant
Dim i As Long, j As Long
'Determine how many delimitations there are. My data always had the format
'data1|data2|data3|...|dataN|, so there was always at least one field.
NumFields = 0
For I = 1 To Len(LineEntry)
If Mid(LineEntry, i, 1) = "|" Then NumFields = NumFields + 1
Next i
ReDim LineFieldArray(1 To NumFields)
'Parse out each element from the string and assign it into the appropriate array value
LastFieldStart = 1
For i = 1 to NumFields
For j = LastFieldStart To Len(LineEntry)
If Mid(LineEntry, j , 1) = "|" Then
LineFieldArray(i) = Mid(LineEntry, LastFieldStart, j - LastFieldStart)
LastFieldStart = j + 1
Exit For
End If
Next j
Next i
ParseLineEntry = LineFieldArray
End Function
You then use another routine to add the connection in (I am using ADODB). My format for entries was TableName|Field1Value|Field2Value|...|FieldNValue|:
Dim InsertDataCommand as String
'LineArray = array populated by ParseLineEntry
InsertDataCommand = "INSERT INTO " & LineArray(1) & " VALUES ("
For i = 2 To UBound(LineArray)
If i = UBound(LineArray) Then
InsertDataCommand = InsertDataCommand & "'" & LineArray(i) & "'" & ")"
Else
InsertDataCommand = InsertDataCommand & LineArray(i) & ", "
End If
Next i
Just keep in mind that you will have to build some case handling into this. For example, if you have an empty value (e.g. Val1|Val2||Val4) and it is a string, you can enter "" which will already be in the ParseLineEntry array. However, if you are entering this into a number column it will fail on you, you have to insert "Null" instead inside the string. Also, if you are adding any strings with an apostrophe, you will have to change it to a ''. In sum, I had to go through my lines character by character to find these issues, but the concept is demonstrated.
I built the table programmatically too using the same parsing function, but of this .csv format: TableName|Field1Name|Field1Type|Field1Size|...|.
Again, this is a big problem you are tackling, but I hope this answer helps you with the less straight forward parts.

Access VBA How can I filter a recordset based on the selections in a multi select list box?

I am trying to use the OpenForm function to filter based on the selections in a multi select list box. what is the correct syntax for this, or is there a better way to go about it? For the sake of example let's say:
List Box has options Ken, Mike, and Sandy.
Car has options Car1, Car2, and Car 3. All cars are owned by 1 or more people from that list box.
If someone from the list box is selected, I would like to open a form containing the cars owned by those people selected.
Thank you!
Ok So I figured out a way to do it:
Create a string to hold a query
Use a For loop to populate the string based on each item selected
Put that string as a filter in the OpenForm command.
Here is the specific code I used to to it. My example in the original post used Cars and People, but my actual context is different: Estimators and Division of Work are the filters. Let me know if you have any questions about it if you're someone who has the same question! Since it might be confusing without knowing more about what exactly I'm trying to accomplish.
Dim strQuery As String
Dim varItem As Variant
'query filtering for estimators and division list box selections
strQuery = ""
If Me.EstimatorList.ItemsSelected.Count + Me.DivisionList.ItemsSelected.Count > 0 Then
For Each varItem In Me.EstimatorList.ItemsSelected
strQuery = strQuery + "[EstimatorID]=" & varItem + 1 & " OR "
Next varItem
If Me.EstimatorList.ItemsSelected.Count > 0 And Me.DivisionList.ItemsSelected.Count > 0 Then
strQuery = Left(strQuery, Len(strQuery) - 4)
strQuery = strQuery + " AND "
End If
For Each varItem In Me.DivisionList.ItemsSelected
strQuery = strQuery + "[DivisionID]=" & varItem + 1 & " OR "
Next varItem
strQuery = Left(strQuery, Len(strQuery) - 4)
End If
Using the JOIN function for cleaner and safer code
When you find yourself repeatedly building incremental SQL strings with delimiters like "," "AND" "OR" it is convenient to centralize the production of array data and then use the VBA Join(array, delimiter) function.
If the interesting keys are in an array, a user selection from a multiselect listbox to build a SQL WHERE fragment for the form filter property could look like this:
Private Sub lbYear_AfterUpdate()
Dim strFilter As String
Dim selction As Variant
selction = ListboxSelectionArray(lbYear, lbYear.BoundColumn)
If Not IsEmpty(selction) Then
strFilter = "[Year] IN (" & Join(selction, ",") & ")"
End If
Me.Filter = strFilter
If Not Me.FilterOn Then Me.FilterOn = True
End Sub
A generic function to pick any column data from selected lisbok rows may look like this:
'Returns array of single column data of selected listbox rows
'Column index 1..n
'If no items selected array will be vbEmpty
Function ListboxSelectionArray(lisbox As ListBox, Optional columnindex As Integer = 1) As Variant
With lisbox
If .ItemsSelected.Count > 0 Then
Dim str() As String: ReDim str(.ItemsSelected.Count - 1)
Dim j As Integer
For j = 0 To .ItemsSelected.Count - 1
str(j) = CStr(.Column(columnindex - 1, .ItemsSelected(j)))
Next
ListboxSelectionArray = str
Else
ListboxSelectionArray = vbEmpty
End If
End With
End Function
A few array builders in the application library and coding can be made look more VB.NET

VB 2010 search CSV records - match search term to return records

I have a csv file with 8 fields and multiple records.
I would like to search the ID field (the first field) by entering a search term in a text box, find the matching record/s and display the full record/s on the VB form in a multi-line text box. I would also like to search by date to find all dates ending in a given year e.g. 2009, with all matching full record/s being returned.
I’ve got so far with the code below, and can return all data in the file but haven’t been able to achieve the search – I tried the commented-out IF statement but couldn’t get it working.
Sample CSV follows the code below.
Any help would be great. Thanks.
Imports System.IO
Public Class Form1
Private Sub btnSearchName_Click(sender As System.Object,...
Dim fileIn As String
Dim fileRows(), fileFields() As String
fileIn = "C:\SuppliersSearch_Test\suppliers.csv"
Label1.Text = String.Empty
If IO.File.Exists(fileIn) Then
Dim fileStream As StreamReader = File.OpenText(fileIn)
fileRows = fileStream.ReadToEnd().Split(Environment.NewLine)
For i As Integer = 0 To fileRows.Length - 1
fileFields = fileRows(i).Split(",")
If fileFields.Length >= 8 Then
' ?? loop to see if field0 contains the inputted surname, return the record
'then check the next record until ALL records checked and matching ones returned
‘ if fileFields(0) = txtSearch.text then
txtResults.Text += fileFields(0) & ", " & fileFields(1) & ", " & fileFields(3) & ", " & fileFields(4) & ", " & fileFields(5) & ", " & fileFields(6) & ", " & fileFields(7)
End If
Next
Else
txtResults.Text = fileIn & " not found."
End If
End Sub
End Class
Sample CSV data. To aid clarity, each record ends with ".com":
Supp1,1 Blue,1 Socks,01/01/2008,1 SocksSupplier,1 Socks supp
address,1 Socks phone,1 Socks#socks.com Supp2,2 Pink,2
Shoes,01/05/2009,2 ShoesSupplier,2 Shoes supp address,2 Shoes supp
phone,2 Shoes#shoes.com Supp3,3 Red,3 Bag,04/03/2009,3 BagSupplier,3
Bag supplier adress,3 Bag supp phone,3 bags#bags.com Supp4,4 Gren,4
Tie,05/03/2007,4 TieSupplier,4 Tie Supplier address,4 Tie supp phone,4
tie_supp#ties.com Supp5,5 Grey,5 Suit,13/05/2009,5 SuitSupplier,5 Suit
Supplier address,5 Suit supp phone,5 suitsupp#suits.com Supp6,6
Black,6 Skirt,14/05/2008,6 SkirtSupplier,6 Skirt Supplier address,6
Skirt supp phone,6 skirtsupp#skirts.com