2013-03-18 61 views
2

我希望得到您对下面的帮助。VBA中的字符串分隔问题

我需要分离VBA中的一些数据,以便它可以设置为单独的变量以用于文件命名系统。

我有以下代码:

Sub StripSlash1() 
Dim strVal As String, strVal2 As String, strVal3 As String, strVal4 As String 

'strVal = "jack\tom\rich\Nicolson\KingMcManaman" 
'strVal = "L:\Pictures\A B C\A5 GROUP\A5 KHAKI\f" 
strVal = "L:\Pictures\A B C\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在启动3点不同的选择,数据上运行测试的代码。在不同的情况下,\的数量可能会有所不同。

我们需要的结果是:

数据集1 strVal2 = KingMcManaman strVal3 =尼科尔森

数据集2 strVal2 = F strVal3 = A5卡其

数据集3 strVal2 = BPD strVal3 = A5 GROUP

我将不胜感激您的意见,因为我已经在这一天没有运气。

问候,

山姆

回答

8

请考虑使用Split功能,做您的情况如下:

strVal = "L:\Pictures\A B C\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 

等等......

+0

谢谢。我用这个,它工作的一种享受。 – SCGB 2013-03-18 18:05:59

+0

+1有效完成。 – brettdj 2013-03-18 22:28:57

1
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 
+0

谢谢。我没有使用这个,因为Kaz Jaw早先的回答对我来说非常完美。 – SCGB 2013-03-18 18:06:38