问题与VBA中的string分离

请感谢您的帮助。

我需要在VBA中分离一些数据,以便将其设置为单独的variables,以便在文件命名系统中使用。

我有以下代码:

Sub StripSlash1() Dim strVal As String, strVal2 As String, strVal3 As String, strVal4 As String 'strVal = "jack\tom\rich\Nicolson\KingMcManaman" 'strVal = "L:\Pictures\ABC\A5 GROUP\A5 KHAKI\f" strVal = "L:\Pictures\ABC\A5 GROUP\BPD" Cells(2, 5).Formula = strVal strVal2 = Right(strVal, InStr(strVal, "\") - 1) Cells(2, 6).Formula = strVal2 strVal4 = Left(strVal, InStrRev(strVal, "\") - 1) Cells(2, 7).Formula = strVal4 strVal3 = Right(strVal4, InStr(strVal4, "\") - 1) Cells(2, 8).Formula = strVal3 End Sub 

开始时的三个strVal是用于运行代码以testing代码的数据的三种不同select。 在不同的情况下,\的数量可能会有所不同。

我们需要的结果是:

数据集1 strVal2 = KingMcManaman strVal3 = Nicolson

数据集2 strVal2 = f strVal3 = A5 KHAKI

数据集3 strVal2 = BPD strVal3 = A5 GROUP

我会很感激你的意见,因为我一直在这一天,没有运气。

问候,

山姆

请考虑使用Splitfunction,在你的情况下做到以下几点:

 strVal = "L:\Pictures\ABC\A5 GROUP\BPD" Dim arrVal As Variant arrVal = Split(strVal, "\") 

要获得strVal一部分,你必须记住arrVal是一个数组:

 strVal2 = arrVal(UBound(arrVal)) 'result: BPD strVal3 = arrVal(UBound(arrVal)-1) 'result: A5 GROUP 

等等…

 Sub Tester() Dim s, arr s = "aaa\bbb\ccc\d\eee" arr = Split(s, "\") With ActiveSheet.Cells(2, 5) .Value = s .Offset(0, 1).Resize(1, UBound(arr) + 1).Value = arr End With End Sub