Reputation: 367
I'm looking for a Macro that will use a 'Find and replace' function but for the "alt Text" of an image.
Basically, I'd like to
I've looked everywhere and I can't find anything on this, can anyone help me? I don't need any dialog boxes for this, I'd just like to enter the search and replacement criteria inside the code if possible.
Thanks in advance :)
PS: I already have code that will go into the header of my document, insert an image then enter it's alt text value. It's the 'Find' function I'm struggling with.
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
Upvotes: 1
Views: 5303
Reputation: 367
After using this for a while now, I've made it even simpler
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
Upvotes: 0
Reputation: 367
So with the Help of Manu and KazJaw We got to the bottom of this.
Here is the correct and working code with my own additions to fight off errors :)
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
Then:
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
Thanks again for all your help!
Upvotes: 2
Reputation: 12745
For searching a picture by alt text, you can use a function like this:
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
and use it like this:
Dim myPic as InlineShape
Set myPic = getPictureByAltText("YourAltText")
myPic.Delete
Upvotes: 2