Vba word заменить картинку

  • Remove From My Forums
  • Question

  • Hello, 

    I am quite fresh to Word VBA object model, therefore my code examples may be far away of proper solution. I will appreciate any help, hint which can help.
    Here is my problem:

    On my Word document I have many pages. On each page I have picture inserted.
    I was able to remove old picture and add new one in the same place where the old was. Here is my routine:

    Set oWrd = wrdApp.Documents.Open(sPath)
      For i = oWrd.Shapes.Count To 1 Step -1
         
        With oWrd.Shapes(i)
           .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
           .RelativeVerticalPosition = wdRelativeVerticalPositionPage
            dTop = .Top
            dLeft = .Left
            dHeight = .Height
            dWidth = .Width
            .Delete
         End With
    
         Set sh = oWrd.Shapes.AddPicture(sPathPicture, , True, dLeft - oWrd.PageSetup.LeftMargin, dTop - oWrd.PageSetup.TopMargin, dWidth, dHeight)
      
      Next i
    oWrd.Close True

    I’ve noticed that new pictures are added always on the first page. I believe that ‘top’ is being measured from the top of the ‘current’ page. 

    I’ve googled a little bit and found this piece of code:

    Set sh = oWrd.Shapes.AddPicture(sPathPicture, , True, dLeft - oWrd.PageSetup.LeftMargin, dTop - oWrd.PageSetup.TopMargin, dWidth, dHeight, oWrd.Range.GoTo(1, 2, PageNumber))

    but I have no idea how to check the ‘pagenumber’ of respective shape.

    To sum up:
    I would like to delete all pictures from all pages (above routines do the job) and add new picture at the same coordinates on the same pages. 

    Thanks in advance for your help

    • Edited by

      Saturday, August 4, 2012 8:08 AM

Answers

  • Hello, 

    I have posted on Word Developer forum and I get an answer!

    Please find it here: direct link

    • Marked as answer by
      Maciej_wroclaw
      Sunday, August 5, 2012 6:57 PM

  • #1

Experts, please, I need help.

How do I replace a figure (type 13, msoPicture) in a Word document by a figure that is on the clipboard, maintaining the characteristics (position, alignment, page size) of the image that is in the Word?

What happens is that I have a macro in Excel that runs through all the worksheets in a workbook, individually copying intervals and graphics, previously defined and pasting these as .PNG or .WMF objects within a Word document.

The macro already does the same thing in PowerPoint and works perfectly, but there are days when I’m trying to do the same thing in Word and I can not. Always occurs some different error.

I am using MS Office 2013 32-bits over Windows 8.1 64-bits

I appreciate any help and apologize for my bad English.

Assuming the images are formatted in-line and are located in the header & footer, respectively, following code should do the job for all documents in the selected folder — just add the paths & names for the images in the ‘FileName:=»»‘ variables.

Sub UpdateImages()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, strDocNm As String, sWdth As Single
Dim wdDoc As Document, wdHdFt As HeaderFooter, wdRng As Range, wdIshp As InlineShape
strDocNm = ActiveDocument.FullName
strFolder = GetFolder: If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "*.doc", vbNormal)
While strFile <> ""
  If strFolder & "" & strFile <> strDocNm Then
    Set wdDoc = Documents.Open(FileName:=strFolder & "" & strFile, AddToRecentFiles:=False, Visible:=False)
    With wdDoc
      With .Sections(1)
        For Each wdHdFt In .Headers
          With wdHdFt
            If .Exists Then
              With .Range
                If .InlineShapes.Count > 0 Then
                  Set wdRng = .InlineShapes(1).Range
                  With .InlineShapes(1)
                    sWdth = .Width
                    .Delete
                  End With
                  Set wdIshp = .InlineShapes.AddPicture(Range:=wdRng, FileName:="")
                  With wdIshp
                    .LockAspectRatio = True
                    .Width = sWdth
                  End With
                End If
              End With
            End If
          End With
        Next
        For Each wdHdFt In .Footers
          With wdHdFt
            If .Exists Then
              With .Range
                If .InlineShapes.Count > 0 Then
                  Set wdRng = .InlineShapes(1).Range
                  With .InlineShapes(1)
                    sWdth = .Width
                    .Delete
                  End With
                  Set wdIshp = .InlineShapes.AddPicture(Range:=wdRng, FileName:="")
                  With wdIshp
                    .LockAspectRatio = True
                    .Width = sWdth
                  End With
                End If
              End With
            End If
          End With
        Next
      End With
      .Close SaveChanges:=True
    End With
  End If
  strFile = Dir()
Wend
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function

As you can see, even addressing header & footers is itself not straightforward (a Section can have three of each) and, as Cindy said, there is no VBA equivalent of the UI’s ‘Change picture’ button.

0 / 0 / 0

Регистрация: 28.03.2015

Сообщений: 6

1

28.03.2015, 12:38. Показов 4198. Ответов 4


Студворк — интернет-сервис помощи студентам

Добрый день.
Прошу помочь с макросом VBA для использования в MS WORD.
На входе папка со следующими документами —
1) Документ MS WORD отчет.doc (либо .docx)
2) Изображение1 — Scheme.jpg
3) Изображение2 — Start.png (либо Start.jpg)
4) Изображение3 — End.png (Либо End.jpg)

Задача:
В документе необходимо заменить слова СХЕМА АВТОДОРОГИ на изображение Scheme.jpg, ФОТО НАЧАЛА на изображение Start.png (либо Start.jpg), ФОТО КОНЦА на изображение End.png (Либо End.JPG).

На данный момент все изображения имеют разный размер, но в принципе их можно привести к одному и тому же размеру при помощи ImageResizer.

Исходные данные во вложении.
Ссылка на конечный рез-т — http://dropmefiles.com/GgArN (не прошло по весу)
Заранее спасибо!!!



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

28.03.2015, 13:53

2

По ссылке — «файлы удалены пользователем».
Обработайте картинки так, чтобы они умещались на страницу вместе с предшествующим текстом.
Макрос:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Sub Макрос1()
Const TXT = "схема автодороги|фото начала|фото конца" 'заменяемый текст, разделитель |
Const FOTO = "Scheme|Start|End"                       'названия соотв. фото без расширения
Dim aTxt, aFoto, i, s
  aTxt = Split(TXT, "|")
  aFoto = Split(FOTO, "|")
  Selection.HomeKey Unit:=wdStory
  With Selection.Find
    .ClearFormatting
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    For i = 0 To UBound(aTxt)
      .Text = aTxt(i)
      If .Execute Then
        s = Dir(ThisDocument.Path & "" & aFoto(i) & ".*")
        If s <> "" Then Selection.InlineShapes.AddPicture _
          FileName:=ThisDocument.Path & "" & s, LinkToFile:=False, SaveWithDocument:=True
      End If
    Next
  End With
End Sub



1



0 / 0 / 0

Регистрация: 28.03.2015

Сообщений: 6

28.03.2015, 15:41

 [ТС]

3

Все работает!
Есть возможность доработать данный макрос, чтобы его можно было запускать не открывать документ отчета, т.е. при его запуске он требовал указать папку, в которой бы лежал полный набор исходных данных (документ, схема, фото1, фото2) и автоматически вставлял его в WORD?



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

28.03.2015, 19:24

4

Лучший ответ Сообщение было отмечено КостяВолков как решение

Решение

КостяВолков,

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Sub Volkov()
Const TXT = "схема автодороги|фото начала|фото конца" 'заменяемый текст, разделитель |
Const FOTO = "Scheme|Start|End"                       'названия соотв. фото без расширения
Dim aTxt, aFoto, i, s, p
  With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Выбор папки"
    If Not .Show Then Exit Sub
    p = .SelectedItems(1) & ""
  End With
  s = Dir(p & "отчет.doc*")
  If s = "" Then MsgBox "Файл 'отчет.doc(x)' не найден", vbExclamation: Exit Sub
  Documents.Open p & s
  aTxt = Split(TXT, "|")
  aFoto = Split(FOTO, "|")
  Selection.HomeKey Unit:=wdStory
  With Selection.Find
    .ClearFormatting
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    For i = 0 To UBound(aTxt)
      .Text = aTxt(i)
      If .Execute Then
        s = Dir(p & aFoto(i) & ".*")
        If s <> "" Then Selection.InlineShapes.AddPicture _
          FileName:=p & s, LinkToFile:=False, SaveWithDocument:=True
      End If
    Next
  End With
End Sub



0



0 / 0 / 0

Регистрация: 28.03.2015

Сообщений: 6

28.03.2015, 20:26

 [ТС]

5

Казанский, все работает. Огромное спасибо!



0



I have the following VBA code that finds the placeholder text (FindText) in all active documents and replaces the text with an image. This code works fine when the text is in the document body; However, if the placeholder text is in the document header, the text does not get replaced with the image.

My question is, How do I replace the placeholder text with the image if the text is in the header of the document?

Sub InsertImagesAllDocuments()

Dim n, c As Integer
n = Application.Documents.Count
c = 1

Dim r As range

Windows(c).Activate


Do
Dim imageFullPath As String
Dim FindText As String
imageFullPath = "C:Logo.jpg"
FindText = "TextPlaceholder"
    With Selection
    .HomeKey Unit:=wdStory

    With .Find
        .ClearFormatting
        .text = FindText
        ' Loop until Word can no longer
        ' find the search string, inserting the specified image at each location
        Do While .Execute
            Selection.MoveRight
            Selection.InlineShapes.AddPicture FileName:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True
        Loop

    End With
End With


    c = c + 1

    On Error Resume Next
    Windows(c).Activate

Loop Until c > n



 End Sub

asked Dec 12, 2013 at 19:10

user1783736's user avatar

you will want to open the header in order to replace the text. You can do so with this line of code

ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
'now the header is accessible, run your code
   With Selection
    .HomeKey Unit:=wdStory

        With .Find
        .ClearFormatting
        .text = FindText
        ' Loop until Word can no longer
        ' find the search string, inserting the specified image at each location
        Do While .Execute
            Selection.MoveRight
            Selection.InlineShapes.AddPicture FileName:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True
        Loop

    End With
End With

answered Dec 12, 2013 at 19:26

Sorceri's user avatar

SorceriSorceri

7,8101 gold badge28 silver badges38 bronze badges

1

Like this post? Please share to your friends:
  • Vba word замена таблицы
  • Vba word выбрать строку в таблице
  • Vba word выбрать строки
  • Vba word выбрать все
  • Vba word выбрать весь текст