简体   繁体   中英

How do I remove everything to the left of a specific character using VBA?

So my question is this, how would I go about creating a VBA Macro where it will automatically cut the string after the 6th _ ? What I mean by this is the following: 例子

As you can see it cuts everything prior of the 6th _ this is what I want to accomplish with the VBA macro. The reasoning behind the macro is due to other variances that I'll be adding in later for further automation. I know how to write it with an excel formula like so:

=RIGHT(SUBSTITUTE(A16,"_",CHAR(10),6),LEN(A16)-FIND(CHAR(10),SUBSTITUTE(A16,"_",CHAR(10),6),1)+1)

But I'm not sure how to write this in VBA format for it to work properly. I have tried to mimic an example from a website I found and this only works for the first underscore, I've tried to modify it so it would work correctly but keep running into errors. Here is the code I used:

Sub Test()

Dim K As Long
Dim LR As Long
LR = Cells(Rows.Count, 1).End(xlUp).Row

For K = 2 To LR
 Cells(K, 2).Value = Right(Cells(K, 1).Value, Len(Cells(K, 1)) - InStr(1, Cells(K, 1).Value, "_"))

Next K

End Sub

Any help would be awesome, and if any clarification is needed I can certainly provide.

Using a UDF:

Function TruncateString(strIn As String) As String
     Dim words As Variant, wordsout As Variant
     words = Split(strIn, "_")

     ReDim wordsout(0 To UBound(words) - 6)
     For i = 6 To UBound(words)
        wordsout(i - 6) = words(i)
     Next
     TruncateString = Join(wordsout, "_")
End Function

You can use that as a formula in your workbook after saving it in a new module like =TruncateString(A1)

I think using the limit argument of Split here might work nicely.

Function StripAfter(ByVal txt As String, ByVal delimiter As String, ByVal occurrence As Long) As String
    Dim x As Variant
    x = Split(expression:=txt, delimiter:=delimiter, limit:=occurrence + 1)

    StripAfter = x(UBound(x))
End Function

Called as a UDF: =SplitAfter(A1,"_",6) .

在此处输入图像描述

EDIT:

With your current code, change:

Cells(K, 2).Value = ...

to

Cells(K, 2).Value = StripAfter(Cells(K, 1).Value, "_", 6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM