如何从VBA字符串数组中提取第n个元素?
我有一个字符串,例如:TEST - 2017/01/20 = Invoice
我希望尽可能简洁地提取第2和第3个元素。我正在尝试像这样的Javascripty,它不起作用,所以必须有一个VBA方式:
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"
答案 0 :(得分:5)
可能的解决方案
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"
答案 1 :(得分:3)
我会使用@ h2so4的替换解决方案(特别是如果它是与工作相关的任务),但是如果你喜欢" fancy"编码,这也有效:
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