VB.NET how to convert Object(,) to String() - arrays

i am currently ready data from excel per EPPlus interface. My Excel is a csv file.
I've already the data available in a object(,) property (for me a unknown format).
Which format is that? How can i convert it to a String Array?

If you mean like this...
Private Class TestIt
Dim strvar1 As String = Nothing
Dim strvar2 As String = Nothing
Dim Split As Object = MyFunc("A")
strvar1 = Split(0)
strvar2 = Split(1)
End Class
'Extra class or something
Public Function MyFunc(Test As String) As Object
Dim var1 As String = Nothing
Dim var2 As String = Nothing
Select Case (Test)
Case "A"
var1 = "one"
var2 = "two"
Case "B"
var = "three"
var2 = "four"
End Select
Return {var1, var2}
End Function

Sorry I didn't realized that it was a two-dimensional array.
The Problem was to find out the maximum number of each dimension.
I've found the following functions:
Array.getUpperBound(dimension)
So that solves my problem.
But many thanks for your fast answer!!

Related

How Do You Return True If A String Contains Any Item In An Array Of String With LINQ in VB.NET

I could not find this question on stack overflow but if it is here, please let me know and I will take it down.
Using LINQ in VB.NET, how do you return True if a string contains one of the items in an array of strings?
This is this is the code in multiple lines. How do you do this in one line with LINQ in VB.NET?
Sub Main
Dim endPointTimeoutText As Array = {"endpoint timeout", "endpoint is not available"}
Dim strResult As String = "endpoint is not available sample text."
Dim booleanResult As Boolean = False
For Each item As String In endPointTimeoutText
If strResult.Contains(item) Then
booleanResult = True
Exit For
End If
Next
Console.WriteLine(booleanResult) 'Only included this for the example
End Sub
The expected result would be 'True' or 'False' depending on if the string (strResult) contained one of the values in the Array Of Strings (endPointTimeoutText)
You turn it around, mentally - don't ask "for this string X, which of these things in this array are in that string", you ask "for this array of strings, which of them are in this one string X":
Dim whichStringsArePresent = endPointTimeoutText.Where(Function(ett) strResult.Contains(ett))
Dim firstImeoutStringFound = endPointTimeoutText.FirstOrDefault(Function(ett) strResult.Contains(ett))
Dim wasATimeout = endPointTimeoutText.Any(Function(ett) strResult.Contains(ett))
etc
By the way it would make your code read more nicely if you make it so that Collections of things have plural names. Consider something more like this:
Dim wasATimeout = endPointTimeoutTexts.Any(Function(ett) strResult.Contains(ett))
It's subtle, but significant in terms of readability
Thank you Caius Jard for your help on this. I am going to post the complete program for what I'm going to use as the answer below.
I needed to use a List instead of an Array so that I could use the 'Any()' method. Thanks again Caius, I really appreciate it!
Sub Main
Dim endPointTimeoutText As String = "endpoint timeout,endpoint is not available"
Dim endPointTimeoutList As New List(Of String)
Dim strResult As String = "endpoint is not available sample text."
endPointTimeoutList = endPointTimeoutText.Split(",").ToList()
Dim areAnyStringsPresent As Boolean
areAnyStringsPresent = endPointTimeoutList.Any(Function(itemInEndPointTimeoutList) strResult.Contains(itemInEndPointTimeoutList))
Console.WriteLine(areAnyStringsPresent)
'This code produces the following output:
'True
End Sub

How to extract a value from an array in excel with VBA

In my table, I have a cell A1 containing an array as string with the following format: [{'type':'general', 'name':'light'},{'type':'brand', 'name':'lighti'},{'type':'misc', 'name':'Sale%'}]
Now I want to create a new sheet, with the name of the brand "lighti" as separate cell-value. This means: I want to get the value in A1, find type "brand" and return the name of the brand and paste it to A2. That's all.
How can I extract the value of the array by using VBA?
You can use ActiveX ScriptControl with Language set to JScript and parse the string as actual JSON.
Then you can just write a Javascript function that returns the "name" based on the "type". For this you don't need any external libraries / other macro's etc.:
Option Explicit
Public Sub UseScriptControlAndJSON()
Dim JsonObject As Object
Dim resultString As String
Dim ScriptEngine As Object
'get the script control:
Set ScriptEngine = CreateObject("ScriptControl")
ScriptEngine.Language = "JScript"
'Add javascript to get the "name" based on "typeName":
ScriptEngine.AddCode "function findByType(jsonObj, typeName) { for (var i = 0; i < jsonObj.length; i++) { if (jsonObj[i].type == typeName){ return jsonObj[i].name; }}}"
'Get the string and parse it:
Set JsonObject = ScriptEngine.Eval("(" & Range("A1").Value & ")")
'Now get the resulting "name" using the JS function, by passing in "brand" as type:
resultString = ScriptEngine.Run("findByType", JsonObject, "brand")
'Will pop-up: "lighti"
MsgBox resultString
End Sub
Note 1: that the JS function will return the first occurance.
Note 2: Strictly speaking you're not using VBA to extract the value.
Note 3: Tested with 32 bit Excel 2016 on a 64 bit machine; script control is a 32 bit-component - see for example this question+answers - On 64bit you can get it to work with some workarounds as per one of the answers in that link.
You could use a custom function to read value from A1, apply split with search term and parse out the required info. It seems a bit overkill to use a JSON parser though that string is JSON and you could extract that way.
Option Explicit
Public Sub test()
[A2] = GetValue([a1], "brand")
End Sub
Public Function GetValue(ByVal rng As Range, ByVal searchTerm As String) As Variant
'[{'type':'general', 'name':'light'},{'type':'brand', 'name':'lighti'},{'type':'misc', 'name':'Sale%'}]
On Error GoTo errhand
GetValue = Split(Split(rng.Value, "{'type':'" & searchTerm & "', 'name':'")(1), "'")(0)
Exit Function
errhand:
GetValue = CVErr(xlErrNA)
End Function
If you were to use a JSONParser like JSONConverter.bas you could parse the JSON as follows. Note: After adding the .bas to your project you need to go VBE > Tools > References and add a reference to Microsoft Scripting Runtime.
Option Explicit
Public Sub test()
[A2] = GetValue([a1], "brand")
End Sub
Public Function ExtractItem(ByVal rng As Range, ByVal searchTerm As String) As Variant
Dim json As Object, key As Object
json = JsonConverter.ParseJson(rng.Value)
For Each item In json
For Each key In item
If key = searchTerm Then
GetValue = item(key)
Exit Function
End If
Next
Next
ExtractItem = CVErr(xlErrNA)
End Function
Assumng the word brand preceeds the brand name each time then
Function GetNameOfBrand(celltext As String) As String
Dim x As Long
Dim s As String
x = InStr(celltext, "brand")
If x = 0 Then
GetNameOfBrand = ""
Else
s = Mid(celltext, x + 16, Len(celltext) - x + 15)
x = InStr(s, "'")
s = Left(s, x - 1)
GetNameOfBrand = s
End If
End Function

Adding Regex matches to an array

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

adding characters to string vb.net

The ending of the student name should read "2016". Is this the best way to modify the string:
Dim Student As String
If Student.Substring(0, 8) = "JoeBlogs" Then
stg = Student.Insert(0, 3)("2016")
End If
I want the string to read "Joe2016Blogs"
I recommend following the advice in Fabio's answer, however, to answer your specific question, you can do the following:
Dim Student As String = "JoeBlogs"
If Student.Substring(0) = "JoeBlogs" Then
Dim stg as string = Student.Insert(3, "2016")
console.WriteLine(stg)
End If
Which produces the following:
Joe2016Blogs
String concatenation should be avoided when done many thousands of times, but for something quick the following will do it: stg = Student & "2016"
String type is immutable, so in any case you need to create new string.
You can use concatenation
Dim newValue As String = stringVariable + "2016" + anotherStringVariable
or you can use String.Format method
Dim newValue As String = String.Format("{0}2016{1}", firstValue, secondValue);
In VB.NET 14 you can use more readable string interpolation feature
Dim newValue As String = $"{first}2016{second}"
And if you creating string in the loops with unknown amount of variables use StringBuilder
Dim builder As New StringBuilder()
For Each item As String in stringCollection
builder.Append(item)
builder.Append("2016")
End For
Dim allItems As String = builder.ToString()
In your case main problem is to split "JoeBlog" to the name and "blog" word and then put "2016" between

How to assign a set of text values to a string array?

How can I assign a set of text values to an array? Nothing I tried is working!
Months = Array("Jan", "Feb", ..., "Dec")
and others I tried do not work!
Here's something about VB: http://www.devx.com/vb2themax/Tip/18322
Visual Basic doesn't provide any way
to declare an array and initialize its
elements at the same time. In most
cases you end up with setting
individual elements one by one, as in:
Dim strArray(0 To 3) As String
strArray(0) = "Spring"
strArray(1) = "Summer"
strArray(2) = "Fall"
strArray(3) = "Winter"
Under VB4, VB5, and VB6 you can create
an array of Variants on the fly, using
the Array() function:
Dim varArray() As Variant
varArray() = Array("Spring", "Summer", "Fall", "Winter")
but there is no similar function to
create arrays of data types other than
Variant. If you're using VB6, however,
you can create String arrays using the
Split() function:
Dim varArray() As String
' arrays returned by Split are always zero-based
varArray() = Split("Spring;Summer;Fall;Winter", ";")
I'm pretty sure you can only do it like this:
dim months(2) as string
months(0) = "Jan"
months(1) = "Feb"
months(2) = "Mar"
If you're talking about vbscript then this works:
months = Array("may","june","july")
If it's vb.net then:
dim months() as string = {"may","june","july"}

Resources