如何转换此Excel宏以在Word中使用?

时间:2019-03-25 00:48:39

标签: excel vba ms-word word-vba

我发现了一个为Excel编写的宏,它具有我需要的确切功能,但我不知道如何将其转换为可在Word中使用-我对脚本和新的语言/语法非常陌生。我最熟悉的是Aspect脚本语言,这是我从Procomm Plus的使用中学到的。我在这里找到Excel宏:

Find specific text and delete three rows above it

Sub Delete()
Dim find As String: find = "TOT"
Dim rng As Range

Set rng = Sheets("Sheet1").Cells.find(What:=find, After:=Sheets("Sheet1").Cells(1, 1), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True)

If Not rng Is Nothing Then
  rng.EntireRow.Delete
  rng.Offset(-1).EntireRow.Delete
  rng.Offset(-2).EntireRow.Delete
  rng.Offset(-3).EntireRow.Delete
End If

End Sub

我需要宏来查找文本“在'^'标记处检测到的%无效输入”,然后将其删除,以及该短语上方的两行:

Router#show environment all                    ;(let's call this "line -2")
            ^                                  ;(and this would be "line -1")
% Invalid input detected at ‘^’ marker         ;(and "line 0")

这是Cisco路由器的控制台输出(复制/粘贴到Word),短语“在'^'标记处检测到%无效输入”始终相同,但上方的两行可能会有所不同,具体取决于Cisco我使用的命令未被识别。

我认为解决方案可能很简单,但是我被卡住了!

我发现了Word的另一个宏,该宏执行类似的功能,并且-它查找关键短语并删除包含该短语的行,但是同样,我不确定如何扩展它以包括前两行文本:

Sub InvalidInput()
Dim oRng As Word.Range
Set oRng = ActiveDocument.Range
With oRng.Find
  .Text = "Invalid input detected"
  While .Execute
    oRng.Paragraphs(1).Range.Delete
  Wend
End With
End Sub

任何人都可以提出一些可以解决我的问题的修改建议吗?预先非常感谢。

2 个答案:

答案 0 :(得分:0)

这是一个远景,但是请访问 Word ...

中的此宏
Public Sub RemoveUnwantedParagraphs()
    Dim objParagraph As Paragraph, arrToRemove() As Long, lngIndex As Long
    Dim i As Long, x As Long, strSearchFor As String

    strSearchFor = "% Invalid input detected at '^' marker"

    lngIndex = -1

    For i = 1 To ThisDocument.Paragraphs.Count
        Set objParagraph = ThisDocument.Paragraphs(i)

        If Left(objParagraph.Range.Text, Len(strSearchFor)) = strSearchFor Then
            For x = 2 To 0 Step -1
                lngIndex = lngIndex + 1
                ReDim Preserve arrToRemove(lngIndex)
                arrToRemove(lngIndex) = i - x
            Next
        End If
    Next

    On Error GoTo ExitGracefully

    For i = UBound(arrToRemove) To 0 Step -1
        ThisDocument.Paragraphs(arrToRemove(i)).Range.Delete
    Next

ExitGracefully:

End Sub

...尽管在运行之前请帮自己一个忙,备份您的文档!

我不保证它不会无意间塞满整个东西。我已经在Word中进行了有限的开发,但是上面的代码对我有用。

唯一需要注意的是,如果您要搜索的文本包含在第一行或第二行中,则可能会中断。我认为这是意料之中的,尽管如此却无法满足要求。

答案 1 :(得分:0)

假设“行”是单独的段落,请尝试:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "[!^13]@^13[!^13]@^13% Invalid input detected at ‘^94’ marker^13"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute Replace:=wdReplaceAll
  End With
End With
Application.ScreenUpdating = True
End Sub

否则,您将不得不对描述“线条”的内容进行更有意义的描述。

相关问题