Adding Regex matches to an array - arrays

I'm struggling to solve a small bit of code. What the code does is to first load a CSV file, line by line (starting by line 3), and add it to an array. Then run a regex match and I want to insert the value in an array.
This is my working code, it shows a msgbox with the actual matches:
Dim file = "C:\Users\David\Desktop\mycsv.csv"
Dim basestatisticspath = Path.GetDirectoryName(file)
Dim statistics() As String = IO.File.ReadAllLines(file)
'Dim x As Integer = statistics.Length
'ReDim Preserve statistics(x)
Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
Dim linefilename As Match = Nothing
Dim langmatch As Match = Nothing
Dim filename() As String
Dim lang() As String
For i = 2 To UBound(statistics)
langmatch = regexlang.Match(statistics(i))
linefilename = regexlinefilename.Match(statistics(i))
MsgBox(langmatch.Value & linefilename.Value)
Next
That works well and the actual matches is what I want. So my next step was to add each match to an array to then use it to generate other files.
Therefore I ended up with this:
Dim file = "C:\Users\David\Desktop\myscv.csv"
Dim basestatisticspath = Path.GetDirectoryName(file)
Dim statistics() As String = IO.File.ReadAllLines(file)
'Dim x As Integer = statistics.Length
'ReDim Preserve statistics(x)
Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
Dim linefilename As Match = Nothing
Dim langmatch As Match = Nothing
Dim filename() As String
Dim lang() As String
' Set all value line by line
For i = 2 To UBound(statistics)
langmatch = regexlang.Match(statistics(i))
linefilename = regexlinefilename.Match(statistics(i))
lang(i) = langmatch.Value.ToString
filename(i) = linefilename.Value.ToString
MsgBox(langmatch.Value & linefilename.Value)
Next
After adding the below the program crashes on that line
lang(i) = langmatch.Value.ToString
filename(i) = linefilename.Value.ToString
I am assuming you can add the value of a regex match to a certain position of a string, but it seems I am wrong.
I´ve been searching for an answer with no results (at least to my poor understanding).
How could I convert each of the matches to a string and add it to the i position of the array?
Thanks in advance!
UPDATE:
As #Tval explained, I solved it by including the size of the array when declaring it. Thanks!
Dim filename(UBound(statistics)) As String
Dim lang(UBound(statistics)) As String

you need to initialize the array before you can reference it or you'll get a null reference error, also you can't reference an index that doesn't exist yet or you'll get an index out of range exception.
right now your using an array with a fixed length, so if you want to add a value to it you'll have to re-declare it one index larger every time.
If you want an array of a variable length id suggest using a list, so you can just append values to it without any issues
Dim myList = New List(Of String)
For Each foo As String In bar
myList.Add(bar)
Next

Related

How to trim values in an array in VBA?

I got a problem I just cant fix. I have a string, want to split it at ";" (that is working) and then trim the values.
Dim cell As String
Dim objects() As String
cell = Range("X74").Text
objects= Trim(Split(cell, ";"))
I get my error on the Trim-function. I then tried the following approach:
For Each object In objects
object = Trim(object)
Debug.Print object
Next
This works, but doesnt save the trimmed value to my objects-array.
Despite naming your variables objects and object, they are an array of simple Strings resp. a simple String, and in VBA a string is not an object.
In your For Each-Loop, you are copying a string to the variable object, and no matter what you do with it, it doesn't change the content of the objects-array.
If you really need to change the content of the objects-array, use a loop like that:
Dim i As Long
For i = LBound(objects) To UBound(objects)
objects(i) = Trim(objects(i))
Debug.Print objects(i)
Next
And you should think about changing the name of your variables...
I would try to avoid vba names as variables:
Sub tst()
Dim yourcell As String, i As Long
Dim yourobjects() As String
yourcell = Range("X74").Text
yourobjects = Split(yourcell, ";")
For i = LBound(yourobjects) To UBound(yourobjects)
yourobjects(i) = Trim(yourobjects(i))
Debug.Print yourobjects(i)
Next i
End Sub

How to create find/replace add in with two multiline textboxes

I'm trying to create a find and replace macro for use as an add-in. I'd like to do so with a userform containing two multiline textboxes where users can enter the strings they would like to find and replace. I've figured out how to put these strings into arrays, but cannot figure out how to match the 'find' array with the 'replace' array and run a Replace command.
Is there some way to give each entry in each array a value, and match them up? I.e. the first string in the 'find' textbox gets a value of 1, the second gets a value of 2, and the same for the 'replace' textbox. Then the macro replaces any instances of 'find' string value 1 with 'replace' string value 1, and so on.
Here's the code I've figured out so far, thanks in advance for the help.
Private Sub CommandButton1_Click()
Dim Find_text As String
Dim Replace_text As String
Dim Find_lines As Variant
Dim x As Integer
Dim Replace_Lines As Variant
Dim y As Integer
Dim find As String
Dim Replace2 As String
Find_text = Find1.Text
Replace_text = Replace1.Text
Find_lines = Split(FindReplace2.Find1, vbCrLf)
Replace_Lines = Split(FindReplace2.Replace1, vbCrLf)
For x = LBound(Find_lines) To UBound(Find_lines)
find = Find_lines(x)
For y = LBound(Replace_Lines) To UBound(Replace_Lines)
Replace2 = Replace_Lines(y)
Next y
Next x
End Sub

Check If value appears twice in array

I have and array and i want to check if my Dim value is contains in array but i need to check if it appears twice.
Example:
Dim value as String = "AST"
Dim zone_check_list() As String = {"AMST","AST","AST","EET","EDT"}
'if "AST" appeared twice then i will show message box
How about using LINQ :
Imports System.Linq
Dim value as String = "AST"
Dim zone_check_list() As String = {"AMST","AST","AST","EET","EDT"}
Dim isAppearTwice As Boolean = (zone_check_list.Count(Function(x) x = value) = 2)
Console.WriteLine(isAppearTwice)

Visual Basic: How to get entire section before/after a certain character?

I have a string. For example stringone/string2
How do I get the section before the "/" and also after the "/"
Dim Word As String = "stringone/string2"
Dim wordArr As String() = Word.Split("/")
Dim stringBefore As String = wordArr(???)
Dim stringBefore As String = wordArr(???)
What is the next step
Split() returns an Array. The first element is at Index 0 (zero), the second element is at Index 1 (one), etc...
You should check to make sure the returned array is your expected size (at least), otherwise you'll get an error attempting to access an index slot that doesn't exist.
Dim Word As String = "stringone/string2"
Dim wordArr As String() = Word.Split("/")
If wordArr.Length = 2 Then
Dim stringBefore As String = wordArr(0)
Dim stringAfter As String = wordArr(1)
Debug.Print("stringBefore = " & stringBefore)
Debug.Print("stringAfter = " & stringAfter)
End If
*By the way, the code you posted is not VB6, it's VB.Net.

VB.NET Checking for existing files and assigning new Version Numbers to the name?

Alright, this one has been driving me up a wall for the past few hours, and I feel like I can almost taste victory, but I am stuck.
I am writing files into a directory based on user supplied requirements, and this particular section deals with assigning a new Version Number to the new file. So basically, this creates the new file using a naming convention of:
Path\FileName_ver1
Path\FileName_ver2
And so on. The issue is, I cannot figure out how to determine if a file with similiar naming (minus the _ver# string) exists in the directory, and then parse the name to find out the current version number, and then create the new file using the version number and adding 1 to it.
If you look at my current code, the issue at the moment is arising when it goes into the loop, telling me that the array is out of bounds, even though the file does exist within the directory.
Dim strPossibleFilename() As String = Directory.GetFiles(savePath, saveName & "_ver*" & saveExt)
Dim intVersionNumber As Integer = 1
For i = 0 To strPossibleFilename.Length - 1
If File.Exists(strPossibleFilename(i)) Then
Dim fileInfo As New FileInfo(strPossibleFilename(i))
Dim fullName As String
Dim strVersionNumber As String
fullName = fileInfo.FullName
Dim versionPosition As Integer = fullName.IndexOf("_ver")
Dim dotPosition As Integer = fullName.IndexOf(".")
Dim versionCharacterCount As Integer = dotPosition - versionPosition
strVersionNumber = fullName.Substring(versionPosition, versionCharacterCount)
If intVersionNumber < strVersionNumber Then
intVersionNumber = strVersionNumber
End If
End If
Next i
If intVersionNumber > 1 Then
saveLocation = savePath & saveName & "_ver" & intVersionNumber + 1 & saveExt
fstr = New FileStream(saveLocation, FileMode.CreateNew, FileAccess.ReadWrite)
fstr.Write(inBuf, 0, bytesRead)
Else
saveLocation = savePath & saveName & "_ver1" & saveExt
fstr = New FileStream(saveLocation, FileMode.CreateNew, FileAccess.ReadWrite)
fstr.Write(inBuf, 0, bytesRead)
End If
P.S. All of the other functionality works, as far as the writing and everything, I am doing this in multiple places in my code, including assigning other varied strings to file names when one already exists...
Please let me know if you need more information.
EDIT:
Made a couple changes based on the answers given, and now it is finding the file, but this brings up a new problem... So I cannot figure out how to ONLY grab the number that is AFTER "_ver" to assign that to intVersionNumber.. Any ideas?
EDIT 2:
Okay, to solve that issue, I added:
Dim strVersionString As String
And added a few other things, so now the for loop looks like this:
For i = 0 To strPossibleFilename.Length - 1
If File.Exists(strPossibleFilename(i)) Then
Dim fileInfo As New FileInfo(strPossibleFilename(i))
Dim fullName As String
Dim strVersionString As String
Dim strVersionNumber As String
fullName = fileInfo.FullName
Dim versionPosition As Integer = fullName.IndexOf("_ver")
Dim dotPosition As Integer = fullName.IndexOf(".")
Dim versionCharacterCount As Integer = dotPosition - versionPosition
strVersionString = fullName.Substring(versionPosition, versionCharacterCount)
Dim rPosition As Integer = strVersionString.IndexOf("r") + 1
strVersionNumber = strVersionString.Substring(rPosition, strVersionString.Length - rPosition)
If intVersionNumber < strVersionNumber Then
intVersionNumber = strVersionNumber
End If
End If
Next i
And now it is working :D Thanks for all the help!
You are doing it right, I have a sneaking suspicion here with this line
For i = 0 To strPossibleFilename.Length
change it to
For i = 0 To strPossibleFilename.Length -1
and then unless you kissed BillGates daughter and he's pissed off, it should work!
For the second part of your question, how to get the number after the _ver
' consider padding the version number
' with leading zeros
' and using a second underscore
' to make it easier to parse for number
Dim fileName As String = "filename_ver_001"
Dim parts As String() = fileName.Split("_"c)
Dim verNumber As Integer = Integer.Parse(parts(2))
If you add a second underscore, you can use the String.Split to break the filename into an array.
FWIW, if you want a more sortable file list pad out the number with leading zeros. Otherwise filename_ver11 is ordered before filename_ver2

Resources