VBA中的字符串分离问题

2 excel 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
Run Code Online (Sandbox Code Playgroud)

一开始的三个strVal是数据运行代码以测试代码的3种不同选择.\的数量可能因情况不同而有所不同.

我们需要的结果是:

数据集1 strVal2 = KingMcManaman strVal3 = Nicolson

数据集2 strVal2 = f strVal3 = A5 KHAKI

数据集3 strVal2 = BPD strVal3 = A5 GROUP

我很感激你的投入,因为我一直在这一天没有运气.

问候,

山姆

Kaz*_*wor 7

请考虑使用Split在您的情况下执行以下操作的功能:

strVal = "L:\Pictures\A B C\A5 GROUP\BPD"
Dim arrVal As Variant
    arrVal = Split(strVal, "\")
Run Code Online (Sandbox Code Playgroud)

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

strVal2 = arrVal(UBound(arrVal))         'result: BPD
strVal3 = arrVal(UBound(arrVal)-1)       'result: A5 GROUP
Run Code Online (Sandbox Code Playgroud)

等等...