Count a specific word using a Function ans a Sub - vb.net

In VB.net, I want to make a counting program using a Function and a Sub.
There is a textbox to input a date and a button to exercise the programme in Form1.
I have a txt file which was extracted from MS-Excel with sequential date of time at its column A.
And from that txt file, I want to count the number of date(Actually string) such as "18-Jun-12".
The answer showing the count should be in the format of msgbox in the Sub.
I really have no idea how to link a Function and a Sub using variable, because I am just beginner.
Any help will be gratefully accepted.

If the fields are delimited by comma you must be careful since the field itself could contain a comma. Then you cannot differentiate between the value and the delimiter. You either could enclose the fields with quotes to mask them. But then you should use an available CSV parser anyway.
If the values never contain comma and you want a simple solution use File.ReadLines or File.ReadAllLines to read the lines and String.Split to get all fields per line.
Here's a simple approach using a little bit of LINQ to count all lines which contain the searched date (as string):
Dim linesWithThatDate = From line in File.ReadLines("Path to File")
Where line.Split(","c)(0).Trim() = "18-Jun-12"
Dim count = linesWithThatDate.Count()
As an aside, if the user must enter a date you could use a DateTimePicker control instead. Then you should also use Date.Parse(line.Split(","c)(0).Trim()) or Date.TryParse to get a real date.

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.

How to categorise a column in excel based on another column containing value in string with delimiter ; where string can have two separate words

This question is a follow up to a previous query: How to categorise a column in excel based on another column that contains value in string separated by semicolons
I have the following spreadsheet (please click on link below for image):
Raw data and expected output
My question is I want to categorise the raw data so the output is as pictured in B16:B34 and C16:C34. I am trying to categorise people by their interests when their interests are in a column containing strings separated by semicolon with multiple words. The Name can come up multiple times according to their interests where in this case Movie, Action Movie, Music, Rock Music, Jazz Music and Radio.
I have tried the answer provided by #Glitch_doctor:
{=IFERROR(INDEX($B$1:$B$11,SMALL(IF(ISNUMBER(SEARCH(B$15,$C$1:$C$11)),ROW($C$1:$C$11)-ROW(INDEX($C$1:$C$11,1,1))+1),ROW(1:1))),"")}
The issue with the answer is that when a person's interest is actually Action Movie they show up in the Movie categorisation. I am trying to match when their interest is Action Movie they only show up in Action Movie after categorisation. Multiple words doesn't seem to work with SEARCH function.
I tried to replace the SEARCH function with a VBA code:
Function ProjectSearch(ByVal strProj As String, ByVal strVal As String, _
Optional ByVal delimiter As String = ";") As Boolean
Dim i As Long
Dim strSplit() As String
strSplit = Split(strProj, delimiter)
ProjectSearch = False
For i = LBound(strSplit) To UBound(strSplit)
If strSplit(i) = strVal Then
ProjectSearch = True
Exit Function
End If
Next i
End Function
Since I am a newbie it doesn't seem to work. My question is there a way where I can do what I want without VBA? If I do need to use VBA what do I need to do?
Thanks kindly in advance.
Okay, that was much simpler than I was expecting it to be:
=IFERROR(INDEX($C$1:$C$11,SMALL(IF(ISNUMBER(IF(SEARCH(E$15,$D$1:$D$11)=1,SEARCH(E$15,$D$1:$D$11),SEARCH(CONCATENATE("; ",E$15),$D$1:$D$11))),ROW($D$1:$D$11)-ROW(INDEX($D$1:$D$11,1,1))+1),ROW(1:1))),"")
I only changed the ISNUMBER(SEARCH(B$15,$C$1:$C$11)) part to ISNUMBER(IF(SEARCH(E$15,$D$1:$D$11)=1,SEARCH(E$15,$D$1:$D$11),SEARCH(CONCATENATE("; ",E$15),$D$1:$D$11)))
The addition IF statement is saying that if the search finds the single word as the first character in the cell to accept that search into the array, otherwise search beginning with "; " instead.

MS Access query custom function accepting form text input as value

G'day, everyone.
I've been banging my head against this question the whole day through today, and I haven't managed to find any answers, so I'd appreciate your help.
What I have:
An Access form containing a text field
A query which is the form's data source
A custom function called RegExp defined within a module
RegExp takes two values as input: string (obtained from a table) and pattern (obtained from the form). RegExp returns a boolean value which in turn thins out query results.
The function works perfectly fine and as expected, however, this is only the case when the user fills out the text field. If the field is left blank, no results are returned (and the function's not even getting called if that's the case).
So here's what that particular statement within the query looks like:
... AND (RegExp(tblRole.Description,Trim([Forms]![frmFindRole]![txtRegExp]))<>False) AND ...
(Basically, to sum it up, user types in a value into the text field which gets leading and trailing spaces trimmed off, converted to a regular expression inside a VBA module, and then query results get filtered based on what boolean value the function returns).
There is a number of controls on this form, and they worked prior to me adding that txtRegExp text field. Now the query only returns results if txtRegExp is filled out, and I have no idea why. I've tried adding more checks, but the query's too complicated already, and I haven't succeeded.
If additional code samples are required for an answer to be made, I'll be able to provide them tomorrow.
Thank you in advance.
P.S. Would Nz help? If yes, then how would I go about using it?
Based on the few explanations you gave in comments
Suppose that this is code triggered on the KeyUp event :
Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
Me.Requery
End Sub
Store the default SQL for your form's recordsource somewhere in a local variable. In this example I considered that you stored it in SQLdefault string.
Prior to requery, check if the textbox is empty and if yes change your form's recordsource SQL accordingly:
private SQLdefault as string
Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
Dim SQL As String
If Nz(txtRegExp, "") = "" Then
SQL = SQLdefault
SQL = Replace(SQL, "AND (RegExp(tblRole.Description,Trim([Forms]![frmFindRole]![txtRegExp]))<>False)", "")
Me.RecordSource = SQL ' Normally this is enought to requery, if not uncomment below
'Me.Requery
Else
Me.RecordSource = SQLdefault ' Normally this is enought to requery, if not uncomment below
' Me.Requery
End If
End Sub
In this example I just remove the SQL part containning :
AND (RegExp(tblRole.Description,Trim([Forms]![frmFindRole]![txtRegExp]))<>False)
Replace it by something else if that's not correct.
That's obviously not the most elegant solution but it's difficult to provide with the best solution with what you've shown.
I've managed to make it work by modifying my initial query to include a check for the value of txtRegExp.
I am still not entirely sure why it failed with a blank txtRegExp value. I have a feeling the RegExp function somehow didn't fire when provided with NULL as the second parameter.
I am very grateful to Thomas G for all the help he's provided.

How to use UserForm Values for multiple things

I have UserForm1 which is a multipage userform and I am trying to access the information that was gathered through the form in a sub located in Module1. This sub will need to access several different values and do different things with those values so this is going to be a multipart question.
I have the below code in which I attempt to use one of the values as the upper limit of a For Next Loop. However the current problem is that when the code reaches this line it jumps to the Userform_Initialize routine.
For X = 1 To UserForm1.LocalOffer.Value
Second part of this question comes from inside the For Next loop from above. Where I have the below code. Which would ideally allow me to cycle through a series of similarly named Textboxes from the userform. Not even sure if that will work as the code keeps breaking before getting to that part.
Range("B" & X).Value = UserForm1.Controls("LocalTier" & Tier).Value
Last Part of this question if I have a Textbox in the userform that contains a date in the format 1/18/2015 is there a way for me to grab just a portion of that date say for instance just the Day or just the last digit of the year?
I am using Excel 2013 but the file will be ran on Excel 2007
Edit:
Turns out that problem 1 was fixed by not closing the userform with the X button but instead adding a line to hide the userform when you hit the last button. As it turns out my code for the second question worked just fine once i got past that. Only question left is the last one which I have no ideas on.
As from the comments, I see you don't need anymore to know about points 1 and 2, I will hence limit my answer to the point 3.
Last Part of this question if I have a Textbox in the userform that contains a date in the format 1/18/2015 is there a way for me to grab just a portion of that date say for instance just the Day or just the last digit of the year?
You can use either string manipulation, or date conversion.
Let's assume the Textbox is called myDateTextbox
String manipulation
Among the string manipulators that VBA provides, I would cite Left() and Right().
For example:
last_digit_of_the_year = Right(myDateTextbox.Text, 1)
will return you the last character of the string. On the other hand:
first_digit = Left(myDateTextBox.Text,1)
will return you the first digit of the string.
You can use the Len(myDateTextBox.Text) built-in to return the current length of the string.
Date conversion
You can simply convert your string into date using the CDate() function. Please note this function will return an error if you pass an invalid string. If your textbox contains 24/01/1990, you can first convert the string into a date:
myDate = CDate(myDateTextBox.Text)
Hence, you can retrieve day, month or year like this:
myYear = Year(myDate)
myMonth = Month(myDate)
myDay = Day(myDate)
Please note that CDate recognizes date formats according to the locale setting of your system.. Hence, if the format in the TextBox is not the same than the one of your system, then consider manipulating the string before to adapt it to the proper format. For example, if your system has settings DD/MM/YYYY and your textbox shows a MM/DD/YYYY type, you can "adjust it" as follows:
wrongFormat = myDateTextBox.Text
splittedDate = Split(wrongFormat,"/")
goodFormat = splittedDate(1) & "/" & splittedDate(0) & "/" splittedDate(2)
If wrongFormat was 1/18/2014 but your system would like to read it as 18/1/2014, it's now fine because goodFormat will be equal to 18/1/2014 after the split and re-build.

Cutting up a CSV file using split

I have a csv file, when i use the split function, my issue is that the 16th segment of the array has a name in it (in most cases) that has first and last name split by a comma. This obviously causes me issues as it puts my array out of sync. any suggestions on how i can handle this?
the string in the 16th segment is surrounded by "" if that helps, the split function still splits it though.
you can use TextFieldParser as indicated here
I recommend Lumen CSV Library, it can correctly handle field values with commas.
Also it has a very good performance, and a very simple usage.
See the link above, it won't disappoint you.
I think you're missing the point. Split is only good for simple csv parsing. Anything that gets even a little complicated means a lot of extra code. Something like the TextFieldParser is better suited to what you want. However if you must use Split here's one way:
Dim TempArray() As String
Dim Output As New List(Of String)
If SourceString.Contains("""") Then
TempArray = SourceString.Split(""""c)
Output.AddRange(TempArray(0).Split(","c))
Output.Add(TempArray(1))
'If the quoted part of the csv line is at the end of the line omit this statement.
Output.AddRange(TempArray(2).Split(","c))
Else
Output = New List(Of String)(SourceString.Split(","c))
End If
This assumes that the data is strictly organized, except for the quotes, if not you'll have to add validation code.
Split by "," with the quotes instead of just a comma. Don't forget to take care of the first and last quotes on the line.