Get the nth element from an array of VBA strings

How to extract the nth element from a VBA string array?

I have a line like: TEST - 2017/01/20 = Invoice

I want to extract the 2nd and 3rd elements as briefly as possible. I tried something like Javascripty that doesn't work, so there must be a VBA way:

Dim Report As String
Dim CurrLine As String
Dim CurrDate As String
Dim CurrTask As String

CurrLine = "TEST - 2017/01/20 = Invoice"
CurrDate = Trim(Split(CurrLine, '-')[1])
CurrTask = Trim(Split(CurrLine, '=')[1])
Report = Report & CHR(34) & CurrDate & CHR(34) & "," & CHR(34) & CurrTask & CHR(34)

//result: "2017/01/20","Invoice"
+4
source share
2 answers

Possible Solution

Dim Report As String
Dim CurrLine As String
Dim CurrDate As String
Dim CurrTask As String, St 


CurrLine = "TEST - 2017/01/20 = Invoice"
St=Split(replace(CurrLine, "=","-"),"-")
CurrDate = St(1)
CurrTask = St(2)
Report = Report & CHR(34) & CurrDate & CHR(34) & "," & CHR(34) & CurrTask & CHR(34)  //result: "2017/01/20","Invoice"
+4
source

I would use the @ h2so4 solution with a replacement (especially if this is a task-related task), but if you are a fan of the “coding fantasy”, this also works:

Option Explicit

Public Sub Test()

    Dim strtest As String

    strtest = "Test - 2017 / 1 / 20 = Invoice"

    Debug.Print Trim(Split(strtest, "-")(1))
    Debug.Print Trim(Split(strtest, "=")(1))
    Debug.Print Trim(Split(Trim(Split(strtest, "-")(1)), "=")(0))

End Sub
+3
source

Source: https://habr.com/ru/post/1668547/


All Articles