How can I find word in Excel and delete the digit Before?

huangapple go评论80阅读模式
英文:

How can I find word in Excel and delete the digit Before?

问题

我想要拆分这个单词。如果我找到了"ACC",则在VBA代码中删除"ACC"之前的单词。

我找到了这段代码,但它会删除找到的文本之后的单词:

Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="blue", _
    Forward:=True
If myRange.Find.Found = True Then 
myRange.SetRange (myRange.End + 1), ActiveDocument.Content.End
myRange.Delete

如果可能的话,可以使用公式函数吗?请给予建议。

英文:

I would like to split the word. If i found ACC, The word before ACC is delete in vba code

How can I find word in Excel and delete the digit Before?

I found this code but it will delete the word after the found text

Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="blue", _
    Forward:=True
If myRange.Find.Found = True Then 
myRange.SetRange (myRange.End + 1), ActiveDocument.Content.End
myRange.Delete

If it possible can use formula function ? Please suggest

答案1

得分: 1

你可以使用这个公式(而不是VBA):

=MID(A1,FIND("ACC",A1),LEN(A1))

顺便说一下,你发布的代码是用于Word-VBA,而不是Excel-VBA。

英文:

You can use this formula (instead of VBA):

=MID(A1,FIND("ACC",A1),LEN(A1))

Btw: the code you posted is for Word-VBA - not for Excel-VBA

答案2

得分: 1

如果你想用公式来实现,可以使用以下公式:

=IFERROR(RIGHT(A1,LEN(A1)-FIND("ACC",A1)+1),"")

如果你想使用VBA代码:

Sub test()
    Dim ws As Worksheet, rng As Range, arr, lRow As Long
    Dim srchStr As String
    srchStr = "ACC"
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    lRow = ws.Range("D" & Rows.Count).End(xlUp).Row
    Set rng = ws.Range("D1:D" & lRow)
    arr = rng.Value
    Dim i As Long
    For i = 1 To UBound(arr, 1)
        If InStr(arr(i, 1), srchStr) Then
            arr(i, 1) = Mid(arr(i, 1), InStr(arr(i, 1), srchStr))
        Else
            arr(i, 1) = ""
        End If
    Next i
    rng.Offset(, 1).Value = arr
End Sub

这样应该可以实现你的需求。

英文:

If you'd want to do it with a formula, you can use

=IFERROR(RIGHT(A1,LEN(A1)-FIND("ACC",A1)+1),"")
(though Mid is less typing and more used nowadays because of it, just giving you options :p)

and if you'd want to use VBA:

Sub test()
    Dim ws As Worksheet, rng As Range, arr, lRow As Long
    Dim srchStr As String
    srchStr = "ACC"
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    lRow = ws.Range("D" & Rows.Count).End(xlUp).Row
    Set rng = ws.Range("D1:D" & lRow)
    arr = rng.Value
    Dim i As Long
    For i = 1 To UBound(arr, 1)
        If InStr(arr(i, 1), srchStr) Then
            arr(i, 1) = Mid(arr(i, 1), InStr(arr(i, 1), srchStr))
        Else
            arr(i, 1) = ""
        End If
    Next i
    rng.Offset(, 1).Value = arr
End Sub

That should do it as well.

huangapple
  • 本文由 发表于 2023年8月9日 14:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定