Word VBA宏基于图像的Alt文本查找和替换

时间:2014-01-27 10:29:34

标签: image vba replace ms-word word-vba

我正在寻找一个宏,它将使用“查找和替换”功能,但用于图像的“替代文字”。

基本上,我想

  • 根据Alt Text
  • 在文档中查找和图像
  • 删除图片
  • 插入新图片
  • 为新图片提供自己的Alt Text

我到处寻找,我找不到任何东西,有人可以帮助我吗?我不需要任何对话框,如果可能的话,我只想在代码中输入搜索和替换标准。

提前致谢:)

PS:我已经有了进入文档标题的代码,插入图像然后输入它的alt文本值。这是我正在努力的'查找'功能。

Sub ReplaceImage()
'
' ReplaceImage Macro
'
'
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
    ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
    ActivePane.View.Type = wdOutlineView Then
    ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.WholeStory
 Selection.InlineShapes.AddPicture FileName:= _
    "IMAGE_LOCATION", LinkToFile:=False, _
    SaveWithDocument:=True
    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend

Selection.InlineShapes(1).AlternativeText = "ALT_TEXT_VALUE"


End Sub

3 个答案:

答案 0 :(得分:2)

要按替代文字搜索图片,您可以使用以下功能:

Function getPictureByAltText(altText As String) As InlineShape
    Dim shape As Variant

    For Each shape In ThisDocument.InlineShapes
        If shape.AlternativeText = altText Then
            getPictureByAltText = shape
            Exit Function
        End If
    Next
End Function

并像这样使用它:

Dim myPic as InlineShape
Set myPic = getPictureByAltText("YourAltText")
myPic.Delete

答案 1 :(得分:2)

所以在ManuKazJaw的帮助下,我们了解了这一点。

这是正确且有效的代码,我自己添加了以防止错误:)

Function getPictureByAltText(altText As String) As InlineShape
Dim shape As Variant

For Each shape In ActiveDocument.InlineShapes
    If shape.AlternativeText = altText Then
        Set getPictureByAltText = shape
        Exit Function
    End If
Next
End Function

然后:

Sub DeletePicByAltText()

Dim myPic As InlineShape
Set myPic = getPictureByAltText("ENTER ALT TEXT YOU ARE SEARCHING FOR HERE")
If myPic Is Nothing Then
    MsgBox "Your Picture was not found. Check the 'Alt Text' is correct and try again."
    End If
On Error Resume Next
myPic.Delete

End Sub

再次感谢您的帮助!

答案 2 :(得分:0)

现在使用了一段时间之后,我已经让它更简单了

Dim pic as InlineShape
Dim alt as String

Alt = "ENTER ALT TEXT HERE"

For Each pic in activedocument.inlineshapes
    If pic.AlternativeText = Alt Then
        pic.Delete
Exit For
    End If
Next