Manochehr Manochehr - 3 years ago 218 Question

Convert a String to its integer type assigned value

Using Below codes in, I have some variables (HUCROW1,HUCROW2,HUCROW3) which are integer type and a specific value is assigned to each of them.
Then in a loop I try to make HUCROW equal to above variables. HUCROW is string type and I concatenate it with the loop number for example by using "HUCROW" & 1.

HUCROW1 = 66
HUCROW2 = 84
HUCROW3 = 102
HUCROW4 = 120

For j = 1 To 3
Dim HUCROW As String = "HUCROW" & (j)

If ScheduleSht.Cells(HUCROW, 9).Value.Ticks <> Nothing Then
HUCdates(i) = ScheduleSht.Cells(HUCROW, 9).value.Ticks
HUCdates(i) = ScheduleSht.Cells(HUCROW, 9).value.Ticks
HUCdates(i) = 0
End If


My aim is to get HUCROW1 value which is 66, but it doesn't work and give "type mismatch error" on ScheduleSht.Cells(HUCROW, 9).value.Ticks as it doesn't convert the string HUCROW to its assigned number.
Any help on how to convert the string type "HUCROW1" to the assigned integer value to HUCROW1 would be appreciated.

Han Han
Answer Source

I think it's easier to use an array or a dictionary to store and retrive the values.

Array sample (subtract j because an array's index starts from zero)

Dim HUCROWS As Integer() = {66, 84, 102, 120}

For j = 1 To 3
    Console.WriteLine(HUCROWS(j - 1))

Dictionary sample

Dim HUCROWS As New Dictionary(Of String, Integer) From {
    {"HUCROW1", 66},
    {"HUCROW2", 84},
    {"HUCROW3", 102},
    {"HUCROW4", 120}

For j = 1 To 3
    Dim HUCROW As String = "HUCROW" & j

Result of both codes

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download