[英]How do I remove everything to the left of a specific character using VBA?
所以我的問題是,我將如何 go 創建一個 VBA 宏,它將在第 6 個_
之后自動剪切字符串? 我的意思是:
如您所見,它削減了 6 號之前的所有內容_
這就是我想用 VBA 宏來完成的。 宏背后的原因是由於我稍后將添加以進一步自動化的其他差異。 我知道如何使用 excel 公式編寫它,如下所示:
=RIGHT(SUBSTITUTE(A16,"_",CHAR(10),6),LEN(A16)-FIND(CHAR(10),SUBSTITUTE(A16,"_",CHAR(10),6),1)+1)
但我不確定如何以 VBA 格式編寫它才能正常工作。 我試圖模仿我發現的網站上的一個例子,這只適用於第一個下划線,我試圖修改它,使其正常工作但不斷出錯。 這是我使用的代碼:
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
任何幫助都會很棒,如果需要任何澄清,我當然可以提供。
使用 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
將其保存在像=TruncateString(A1)
這樣的新模塊中后,您可以將其用作工作簿中的公式
我認為在這里使用Split
的limit
參數可能會很好。
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
稱為 UDF: =SplitAfter(A1,"_",6)
。
編輯:
使用您當前的代碼,更改:
Cells(K, 2).Value = ...
至
Cells(K, 2).Value = StripAfter(Cells(K, 1).Value, "_", 6)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.