MS Access capture certain group of text, append, and loop onto next section in a long text field - vba

I have a long text field (called "reporttext") that someone is importing a bunch of text that needs to be separated and appended into another table. For each case, there's a "[]" character that is supposed to separate each case. I want my code to look for the first [] and second [], append the text to another table and then loop. So the next case would be the text between the second [] and third [].
Here's my string
Reporttext: [] ksfjjls [] 42244 [] ####
I would want this to append to a new table called "notes" where it would be like this:
Reporttext
ksfjjls
42244
####
I used a macro to count the number of [] in the text file to know how many times to run the loop, but this, along with the rest of my code just isn't happening. I know my code is wrong, but I know with a few tweaks it'll get there. Any help is appreciated.
lengthofnote = Len([reporttext])
start = InStr([reporttext], "[]")
startplus3 = [start] + 3
'find number of cases
firstcase = 1
numcases = StringCountOccurrences([reporttext], "[]")
Dim LCounter As Integer
For LCounter = [firstcase] To [numcases]
revisedreporttext = Mid([reporttext], [startplus3], [lengthofnote])
secondposition = InStr([revisedreporttext], "[]")
nextreporttext = Mid([reporttext], [startplus3], [secondposition])
Add_reporttext = "INSERT INTO notes(reporttext) values ('" & nextreporttext & "');"
DoCmd.RunSQL Add_reporttext
firstcase = firstcase + 1
startplus3 = secondposition
secondposition = secondposition + 4
Next LCounter

#Zev Spitz is correct in that you could use Split() to accomplish this. You could use something like this
Option Compare Database
Option Explicit
Sub SplitLongTextField()
Dim rs As Recordset
Dim reportTextArr
Dim qString As String
Dim i As Long
qString = "SELECT [reporttext] FROM [Table1]" '<- replace [Table1] with the name of your table with the Long Text field
Set rs = CurrentDb.OpenRecordset(qString)
If Not rs.EOF Then
reportTextArr = Split(rs.Fields("reporttext"), "[]")
End If
For i = LBound(reportTextArr) To UBound(reportTextArr)
If Not reportTextArr(i) = "" Then
DoCmd.RunSQL "INSERT INTO notes(reporttext) VALUES('" & reportTextArr(i) & "');"
End If
Next i
rs.Close
End Sub
If you needed to do this for multiple records from your initial table then you could loop through the entire table and loop the operation like
Option Compare Database
Option Explicit
Sub SplitLongTextField()
Dim rs As Recordset
Dim reportTextArr
Dim qString As String
Dim i As Long
qString = "SELECT [reporttext] FROM [Table1]" '<- replace [Table1] with the name of your table with the Long Text field
Set rs = CurrentDb.OpenRecordset(qString)
Do Until rs.EOF
reportTextArr = Split(rs.Fields("reporttext"), "[]")
For i = LBound(reportTextArr) To UBound(reportTextArr)
If Not reportTextArr(i) = "" Then
DoCmd.RunSQL "INSERT INTO notes(reporttext) VALUES('" & reportTextArr(i) & "');"
End If
Next i
rs.MoveNext
Loop
rs.Close
End Sub

Assuming the string always starts with [] and preference is to return a single string, consider:
Replace(Mid(reporttext, 4), "[] ", vbCrLf)

Related

Modify multiple records via listbox based on combobox in Access

I have a form that has a multi-selection listbox based on a query of items that have a specific field that is blank (UserID). I would like to select a UserID from a combobox and click a button to have all selected records modified to have that UserID. (I would also like to update the DateAssigned field to whatever the current date is). CaseID is the unique value in the table.
Sample Form Picture
(The combo box has two columns, the second one has the actual ID I'd want to use).
I've looked at multiple different posts on here like this but I haven't been able to get it to work. Here's an example of a code I found and tried, altered slightly.
Private Sub AssignButton_Click()
Dim lCnt As Long
Dim lID As Long
Dim sSQL_Update As String
Dim sText_1 As String
Dim bSuccess As Boolean
sText_1 = Me.ComboBox
With Me.ToAssignList
For lCnt = 1 To .ListCount
If .Selected(lCnt) Then
lID = .Column(4, lCnt - 1)
'Example update for 1 column
sSQL_Update = "UPDATE MainData SET UserID = '" & sText_1 & "' WHERE CaseID = " & lID & ";"
bSuccess = Update_Statement(sSQL_Update)
End If
Next
End With
End Sub
Public Function Update_Statement(sUpdate_Stmt) As Boolean
Dim db As Database
Set db = CurrentDb
db.Execute (sUpdate_Stmt)
End Function
When I try running this nothing happens.
Thank you!
Hy, Some remarks and tweaks to your code :
First enable the direct screen :
This will enable you to use the debug function.
Is the field : UserID in the table Maindata a text field ? If so, fine, otherwise you should alter the string to :
"UPDATE MainData SET UserID = " & Cint(sText_1) & " WHERE CaseID = " & lID & ";"
Then it would be better to create different functions in a module for what you are trying to do. But ok, this is not your main concern right now...
Try :
Private Sub AssignButton_Click()
Dim lCnt As Long
Dim lID As Long
Dim sSQL_Update As String
Dim sText_1 As String
Dim bSuccess As Boolean
sText_1 = Me.ComboBox
With Me.ToAssignList
For lCnt = 1 To .ListCount
If .Selected(lCnt) Then
lID = .Column(4, lCnt - 1)
'Example update for 1 column
sSQL_Update = "UPDATE MainData SET UserID = '" & sText_1 & "' WHERE CaseID = " & lID & ";"
'
'Check your sql statement and add it to stack overflow if it still is not working
'
Debug.Print sSQL_Update
'
bSuccess = Update_Statement(sSQL_Update)
End If
Next
End With
End Sub
There is should be a logical check in the code bellow to see if the update is done, anyhow, the code bellow should work and return a true value if the update doesn't produce an error... it's not good code but ok.
Public Function Update_Statement(sUpdate_Stmt) As Boolean
Dim Currentdb As Database
Set Currentdb = Currentdb
Call Currentdb.Execute(sUpdate_Stmt, dbSeeChanges)
Update_Statement = True
End Function
Good luck !

Dlookup in side of a Loop Is it possible?

I am "creating" my first loop, I copied code and am trying to get it to work. I have the loop functioning but when I try to do a Dlookup in the middle of the loop it does not work.
I am sure there are some ways to make this code work better, Just trying to retrieve dynamic data for the body of my email.
Here is the relevant part of the loop.
strSQL = "SELECT * FROM emailbody Where EmailMainID = " & Me.EmailMainID
Set rs = CurrentDb.OpenRecordset(strSQL)
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
LookupInfo = rs.Fields("beforetable") & "-" & rs.Fields("beforefield") 'Get Table and Field to lookup
LookupLen = Len(LookupInfo) 'Find how many letters are in the string
SubtractLen = InStr(1, [LookupInfo], "-") ' Find the number of letters to the left
RightCut = LookupLen - SubtractLen ' Find how many are to the right
Table = Left([LookupInfo], InStr(1, [LookupInfo], "-") - 1) ' Set the table value
Field = Right([LookupInfo], RightCut) ' Set the Field Value
InfoInsert = DLookup("Table", "Field", TeamDetailsID = 39)
FreshData = rs.Fields("emailbodyid") & " " & rs.Fields("bodycontent")
LongEmail = EmailMe & FreshData
EmailMe = LongEmail
FreshData = ""
LongEmail = ""
.MoveNext
Wend
End If
.Close
End With
it should be:
InfoInsert = DLookup("Table", "Field", "TeamDetailsID = 39")
or, if you use a variable
InfoInsert = DLookup("Table", "Field", "TeamDetailsID = " & idteam)
So I my most recent test tells me my difficulty is not the loop.
I tested the code this way (Yes I had the field and the table mixed up in the above example)
I get the result in Test2 But not Test1
Dim Table As String
Dim Field As String
Table = TeamDetails
Field = DepartDate
test2 = DLookup("DepartDate", "TeamDetails", "TeamDetailsID = 39")
MsgBox test2
test1 = DLookup("Field", "Table", "TeamDetailsID = 39")
MsgBox test1

Loopings in VB.net with two text boxes

I have two text boxes in a user-input form asking for a VisitID(s) and to set a price.
It then uses the following code to update each VisitID with a single price.
myCmd1.CommandText = "UPDATE tblVisit SET Price = (" & CustomerRefString & ") WHERE VisitID IN (" & VisitIDString & ")"
I understand that the above code loops for each VisitID in the VisitIDString, but how do I loop to allow updating each visitID with the corresponding line in the Price TextBox?
Private Sub btnOk_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim VisitIDString AS String
Dim VisitIDsUpdated As Object
Dim myComma() As Char = {","}
Dim connString As String
Dim DataSourceBase = Report.GetDataSource("Connection")
Dim ConnectionCollection = Report.Dictionary.Connections
connString = ConnectionCollection(0).ConnectionString
VisitIDString = VisitIDTextBox.Text
VisitIDString = VisitIDString.Replace(vbCr, "").Replace(vbLf, ",")
VisitIDString = VisitIDString.Replace(" ", "")
VisitIDString = VisitIDString.TrimEnd(MyComma)
Report.SetParameterValue("VisitIDByte",VisitIDString)
'------------------------------------------------------------------------------------------------------------
Dim CustomerRefString AS String
Dim CusterRefUpdated As Object
Dim myCommaRef() As Char = {","}
'------------------------------------------------------------------------------------------------------------
CustomerRefString = CustomerRefTextBox.Text
CustomerRefString = CustomerRefString.Replace(vbCr, "").Replace(vbLf, ",")
CustomerRefString = CustomerRefString.Replace(" ", "")
CustomerRefString = CustomerRefString.TrimEnd(MyComma)
'------------------------------------------------------------------------------------------------------------
myConn = New SqlConnection(connString) 'after changes
'Create a Command object
myCmd1 = myConn.CreateCommand
myCmd1.CommandText = "UPDATE tblVisit SET Price = (" & CustomerRefString & ") WHERE VisitID IN (" & VisitIDString & ")"
'Open the connection.
myConn.Open()
'Execute the statement and return a single value. If you wanted to return more than 1 value you need to add a loop here.
VisitIDsUpdated = myCmd1.ExecuteScalar()
'Close the database connection.
myConn.Close()
End Sub
There are better ways to create your user interface, but if you have to do it this way (with textboxes), then you can solve the problem easily as long as the user enters the data correctly.
Assuming you have "id" and "price" data that looks something like this:
---------
|ID|PRICE|
---------
|11|1.11 |
|22|2.22 |
|33|3.33 |
---------
The user would paste these values into the VisitIDTextBox textbox:
11
22
33
And the user would paste these values into the Price textbox:
1.11
2.22
3.33
Then your solution relies on the fact that the index number of the item in the VisitIDTextBox textbox would match the index number of the item in the Price textbox.
So you would convert the contents of both textboxes into an array. Below is a simple example of you can do that for the VisitIDTextBox textbox.
'Any character in this array will be used to split the string
Dim sAAA As String = ",|" & vbCrLf
Dim arSplitOnValues() As Char = sAAA.ToCharArray()
'Create an array of visit ID's
Dim arVisitIDs() As String = VisitIDTextBox.Text.Split(arSplitOnValues, System.StringSplitOptions.RemoveEmptyEntries)
After doing the same for the values in the Price textbox, you would now have two arrays; arVisitIDs and arPrices
The index of each item in the arrays would now match up, so you can select from arVisitIDs and arPrices using the same index and get the price that matches the ID.
You can see this by using a simple loop like this:
For iLpr As Integer = 0 To arVisitIDs.GetUpperBound(0)
MessageBox.Show(Me, arVisitIDs(iLpr) & "~" & arPrices(iLpr), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Next iLpr
When run, you'll get three messageboxes with values like this:
11~1.11
22~2.22
33~3.33

There is an issue with my code here, can someone look?

I have a listview box that gets populated with five items. Here's the code that I used to populate it
Dim rs As New ADODB.Recordset
Set rs = New ADODB.Recordset
Dim lvwItem As ListItem
Dim x As Integer
lvwExpenditures.ListItems.Clear
With lvwExpenditures
.FullRowSelect = True
.View = lvwReport
.LabelEdit = lvwManual
.ColumnHeaders.Add , "FldName", "EXPENSES", 2200
.ColumnHeaders.Add , "ID", "ID", 0
End With
g_strSQL = "Select FldName, ID, Label, SortOrder from dbo.tblText_References where fldname ='expenditureitems'"
rs.Open g_strSQL, g_cnDatabase, adOpenStatic
Debug.Print g_strSQL
With rs
Do While Not .EOF
Set lvwItem = lvwExpenditures.ListItems.Add(, , .Fields("Label").Value)
lvwItem.SubItems(1) = .Fields("ID").Value 'Populate Date column
.MoveNext
Loop
End With
Set rs = Nothing
What I'm trying to do is let the user select multiple items, concatenate the items (with a comma) and insert them into a table. Here's the code I have for trying to take the selected items and concatenate them (I built a function), but the issue is, it takes one of the items, and concatonates it three times (when three items were selected in listview). I show the label and save the ID, so the when listview is loaded the ID's go in this order 10,11,12,13,14. On my last try, I selected the top three items and the function converted it to (13,13,13). How do I fix it? I know its a small issue
dim x As Integer
Dim mystring As String
For x = 1 To lvwExpenditures.ListItems.Count
If lvwExpenditures.ListItems(x).Selected = True Then
If x = 1 Then
mystring = lvwExpenditures.SelectedItem.SubItems(1)
Else
mystring = mystring & "," & lvwExpenditures.SelectedItem.SubItems(1)
End If
Else
End If
Next x
dim x As Integer
Dim mystring As String
dim sep as string
sep=", "
For x = 1 To lvwExpenditures.ListItems.Count
If lvwExpenditures.ListItems(x).Selected Then
mystring = mystring & lvwExpenditures.ListItems(x).SubItems(1) & sep
End If
Next x
if mystring<>"" then
mystring=left(mystring,len(mystring)-len(sep)
end if

for loop for a string variable

this is my code -
for i as integer = 0 to rows.count - 1
output &= "Name =" & row(i)("Name")
output &= "lastName =" & row(i)("lastName")
... 50 more fields
next
i need the output to be like this
Applicant1Name = MikeApplicant1lastName = ditkaApplicant2Name = TomApplicant2lastName = Brady ...
how do i do this without putting the following code 50 times -
output &= "Applicant" & i.tostring() + 1 &"Name =" & row(i)("Name")
... and so on.
is there a way to make a for loop and run applicant 1,2,3,4.... in one shot?
thanks
Try:
Dim output as New StringBuilder("")
For i as Integer = 0 To rows.Count - 1
output.append("Applicant" + i.ToString())
Foreach(col as DataColumn in dt.Columns) ' The datatable where your rows are
Dim colName as string = col.ColumnName
output.append(colName & "=" & rows(i)(colName).ToString())
Next
If i < rows.Count - 1 Then output.Append("|")
Next
StringBuilder is faster for string concatenations, and if you keep your rows in a datatable (which I assume is happening because that's how it looks like you're accessing them), then you can just iterate through the columnnames at the top level.
You really cant as you are trying to append 50 different fields.
The only thing you can shorten is the variable name:
Dim strLN as String = row(i)("lastName")
Dim strFirstName as String = row(i)("firstName")
Then you simply put it all together
output &= strLN & strFirstName...etc
looks like you want to create an array of all the fields you have and then include a nested loop.
Dim fields As String() = {"Name", "LastName", "SSN", "Birthdate"}
Dim output As String = ""
For i As Integer = 1 To rows.count
For Each field As String In fields
output = String.Concat(output, "Applicant ", i, field, "=", row(i)(field), " ")
Next
Next