Vba word вставка картинки

Well, first we need to clean up your code a bit, like below. This runs fine on my site — it places the image right at the front of the GraphicImage bookmark, not at the top of the document — but maybe your image is so large it extends to the top?

Dim objWdRange As Word.Range
Dim GraphImage As String
Dim shortString As String
shortString = Range("short").Value '? don't know what this is for
GraphImage = "http://xxx.xxxxx.com/xxx/xxx.png?instrument=Image.png"
wrdApp.Visible = True
    Set wrdDoc = wrdApp.Documents.Open("C:Program FilesMy Dropboxdailystrategy.doc")
    Set objWdRange = wrdDoc.Content '? don't know what this is for
    With wrdDoc
        If .Bookmarks.Exists("shortString ") Then
           .Bookmarks("shortString ").Range.Text = shortString
        End If
     If .Bookmarks.Exists("GraphImage") Then
         Dim wrdPic As Word.InlineShape
         Set wrdPic = .Bookmarks("GraphImage").Range.InlineShapes.AddPicture(FileName:=GraphImage, LinkToFile:=False, SaveWithDocument:=True)
         wrdPic.ScaleHeight = 50
         wrdPic.ScaleWidth = 50
     End If
       .SaveAs "c:temptest.doc"
    End With
    wrdDoc.Close
    Set wrdDoc = Nothing
    wrdApp.Quit
    Set wrdApp = Nothing

EDIT: Jan 11, 2010
The above code was changed to include

 If .Bookmarks.Exists("GraphImage") Then
 Dim wrdPic As Word.InlineShape
 Set wrdPic = .Bookmarks("GraphImage").Range.InlineShapes.AddPicture(FileName:=GraphImage, LinkToFile:=False, SaveWithDocument:=True)
    wrdPic.ScaleHeight = 50
    wrdPic.ScaleWidth = 50
 End If

This sets the picture as an object and then uses the scaling methods ScaleHeight and ScaleWidth to make it 50% smaller in both height and width.

In this article I will explain how you can use VBA for word to insert images to a word document using VBA.


Insert Single Image:

The code below will insert the image “SP_A0155.jpg” from the location “D:StuffBusinessTemp”:

Sub Example1()
Selection.InlineShapes.AddPicture FileName:= _
    "D:StuffBusinessTempSP_A0155.jpg", LinkToFile:=False, _
    SaveWithDocument:=True
End Sub

Result:

Word VBA, Insert Result


Insert Image at Specific Location:

In order to insert the image at a specific location, you will need to move the cursor to that location. There are different methods for moving the cursor around in word using VBA:

  • Word VBA, Go to Specific Line
  • Word VBA, Move Cursor to End of Line
  • Word VBA, Move Cursor to Start of Line
  • Word VBA Bookmarks

In this example I will assume we have created a bookmark at the location we want to insert the image. The bookmark was named “bm1”. Assume we have the following text in the word document:

Word, VBA, Bookmark and text
Assume the image is called “SP_A0155.jpg” with the same location as the previous example,  “D:StuffBusinessTemp”. The code below will insert the image at the location of  the bookmark:


Sub Example2()
'move the cursor to the bookmark
Selection.GoTo What:=wdGoToBookmark, Name:="bm1"
'insert the image
Selection.InlineShapes.AddPicture FileName:= _
    "D:StuffBusinessTempSP_A0155.jpg", LinkToFile:=False, _
    SaveWithDocument:=True
End Sub

Result:

Word, VBA insert Image Result


Insert Image Using Open File Dialog:

You can use open file dialogs to ask the user to select the path of the image to insert. In the example below the user will be asked to select the location of the image to insert:

Sub Example3()
Dim intChoice As Integer
Dim strPath As String

'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
End If
'move the cursor to the bookmark
Selection.GoTo What:=wdGoToBookmark, Name:="bm1"
'insert the image
Selection.InlineShapes.AddPicture FileName:= _
    strPath, LinkToFile:=False, _
    SaveWithDocument:=True
End Sub

 The open file dialog allows the user to select the image to insert:

Word, VBA, Open File Dialog Insert Image


Insert All Images in a Folder:

In the article below I’ve explained how you can use VBA to list all the files in a folder:

  • Find and List all Files and Folders in a Directory

Also in the article below I’ve explained how you can use folder dialogs to ask the user to select a folder:

  • VBA Folder Dialogs

by combining the two and using the code explained in the previous sections we get:

Sub example4()
Dim intResult As Integer
Dim strPath As String
Dim strFolderPath As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer

'the dialog is displayed to the user
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
'checks if user has cancled the dialog
If intResult <> 0 Then
    'dispaly message box
    strFolderPath = Application.FileDialog(msoFileDialogFolderPicker _
        ).SelectedItems(1)
    'Create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Get the folder object
    Set objFolder = objFSO.GetFolder(strFolderPath)
    i = 1
    'loops through each file in the directory and prints their names and path
    For Each objFile In objFolder.Files
        'get file path
        strPath = objFile.Path
        'insert the image
        Selection.InlineShapes.AddPicture FileName:= _
           strPath, LinkToFile:=False, _
           SaveWithDocument:=True
    Next objFile
End If
End Sub

A folder dialog is displayed asking the user to select the folder with the images in:

Word, VBA, Folder Dialog
After selecting a folder, all the images in that folder are inserted in the word document:

Word, VBA, Insert Images Result

You can download the file and code related to this article from the link below:

  • Insert Image.docm

See also:

  • Word VBA, Re-Adjust Caption
  • Word VBA, Loop Through Images
  • Word VBA, Adding Caption to Images
  • Word VBA, Removing Picture Captions
  • Word VBA, Crop Images

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Sub Макрос()

        Dim shape As shape
    Dim FN As String

            ‘ Полное имя файла-рисунка.
    FN = «C:UsersUserDesktopРисунок.png»

        ‘ Вставка неплавающего рисунка и превращение неплавающего рисунка в плавающий.
        ‘ При этом присваиваем рисунку имя ‘shape’ и далее в коде будем обращаться
        ‘ к рисунку по имени ‘shape’.
    Set shape = Selection.InlineShapes.AddPicture(FileName:=FN, LinkToFile:=False, _
        SaveWithDocument:=True, Range:=Selection.Range).ConvertToShape

        ‘ Здесь можете делать нужные действия с рисункам, используя имя ‘shape’.
        ‘ Например, так можно узнать левое положение рисунка.
        ‘ Информация запишется в View — Immediate Window.
    Debug.Print shape.Left

    End Sub

[свернуть]

Понадобилось мне тут в свое время писать много текста в MS Word, вставляя туда картинки. Понимая, что картинки рано или поздно понадобится переделывать, я пришел к необходимости вставки не картинок, а ссылок на них. Но вставить поле мало — крайне желательно еще и подписывать имя вставленной картинки.

При этом файл doc / docx может перемещаться между компьютерами (да, я пользуюсь и DropBox, и Yandex.Drive, и OneDrive). Соответственно надо вставлять относительные пути и подписывать их же. Не очень продолжительный поиск по сети и немного фантазии дали такой вариант:

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

Option Explicit

Public sInitialPath As String

Private Declare Function PathRelativePathToW _
    Lib «shlwapi.dll» (ByVal pszPath As Long, _
    ByVal pszFrom As Long, ByVal dwAttrFrom As Long, _
    ByVal pszTo As Long, ByVal dwAttrTo As Long) _
    As Boolean

     
Private Function GetRelativePath _
  (ByVal sPathFrom As String, _
   ByVal sPathTo As String) As String
   ‘ Определение относительного адреса
   ‘ каталога или файла
   Dim sRelativePath As String
   sRelativePath = Space(260) ‘ резервируем буфер
   
   If PathRelativePathToW(StrPtr(sRelativePath), _
             StrPtr(sPathFrom), vbDirectory, _
             StrPtr(sPathTo), 0) Then  ‘ определили адрес
             ‘MsgBox sRelativePath
     GetRelativePath = Left(sRelativePath, _
        InStr(sRelativePath, vbNullChar) — 1)
   Else  
     GetRelativePath = «*»
   End If
End Function

Public Sub InsertLinkToPicture()
Dim sFileName As String
Dim oField As Field
    With Application.FileDialog(msoFileDialogOpen)
      .Title = «Укажите рисунок»
      .AllowMultiSelect = False
      .ButtonName = «Select»
      .Filters.Clear
      .Filters.Add «Картинки», «*.jpg; *.tiff; *.tif; *.png»
      If sInitialPath = «» Then sInitialPath = Application.ActiveDocument.Path
      .InitialView = msoFileDialogViewList
      If .Show Then sFileName = .SelectedItems(1) Else Exit Sub
    End With
    If Left(Selection.Text, 1) <> Chr(13) Then
      Selection.TypeText Text:=vbCr
    End If
    sFileName = GetRelativePath(Application.ActiveDocument.FullName, sFileName)
    Select Case True
      Case Left(sFileName, 2) = «..»
        sFileName = Right(sFileName, Len(sFileName) — 2)
      Case Left(sFileName, 1) = «.»
        sFileName = Right(sFileName, Len(sFileName) — 1)
    End Select
    If Left(sFileName, 1) = «/» Or Left(sFileName, 1) = «» Then
      sFileName = Right(sFileName, Len(sFileName) — 1)
    End If
    Set oField = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldEmpty, _
      Text:=«INCLUDEPICTURE  « + Chr(34) + _
      Replace(sFileName, «», «/») + _
      Chr(34) + » d « _
      , PreserveFormatting:=True)

     
    If InStr(sFileName, «_35%») Then
      ActiveDocument.Hyperlinks.Add Anchor:=oField.Result, Address:=Replace(sFileName, «_35%», «»), SubAddress:=«»
    End If

   
    Selection.TypeText Text:=vbCrLf + Replace(sFileName, «_35%», «») ‘Right(sFileName, Len(sFileName) — Len(Application.ActiveDocument.Path))
    Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
    Selection.Font.Italic = True
    Selection.Font.Bold = True
    Selection.Font.Color = wdColorRed
    ‘ Selection.Range.HighlightColorIndex = wdGreen
    Selection.EndKey
End Sub

Но, как выяснилось, в MS Office 2013 x64 решение работать не будет (даже если попытаться корректно объявить импорт PathRelativePathToW, VBA отказывается обрабатывать указатели на строки). Поэтому было найдено другое решение:(исходник здесь):

Тогда по Ctrl+Z будет отменяться все целиком, а не по шагам. Нередко рядом с оригинальным файлом я кладу его «уменьшенную» копию (уменьшение выполняется с FastStone Image Viewer, картинка уменьшается до 35%, имя файла оканчивается на «_35%»). Если рядом с оригиналом есть уменьшенный вариант, в поле вставляется «уменьшенная» копия, а подпись идет на нормальный вариант. В результате получилось такое чудо:

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

Option Explicit

Public sInitialPath As String

Public Function GetRelativePath(ByVal sFrom As String, ByVal sTo As String) As String
  GetRelativePath = «»
  Dim sFromTmp As String, sToTmp As String, sTmp As String, bFirst As Boolean
  sFromTmp = «»
  sToTmp = «»
  sTmp = «»
  bFirst = True
  Do While Len(sFrom) > Len(sFromTmp) Or Len(sTo) > Len(sToTmp)
    If Len(sFrom) > Len(sFromTmp) Then
      If Not bFirst Then sFrom = Right(sFrom, Len(sFrom) — Len(sFromTmp) — 1)
        sFromTmp = GetLeftPart(sFrom)
      Else
        sFrom = «»
        sFromTmp = «»
      End If

     
      If Len(sTo) > Len(sToTmp) Then
        If Not bFirst Then sTo = Right(sTo, Len(sTo) — Len(sToTmp) — 1)
          sToTmp = GetLeftPart(sTo)
        Else
          sTo = «»
          sToTmp = «»
        End If

       
        If bFirst And sFromTmp <> sToTmp Then
          Exit Function ‘ Нет общего корня
        Else
          bFirst = False
        End If

       
        If Len(GetRelativePath) > 0 Or sFromTmp <> sToTmp Then
          If Len(sFromTmp) > 0 Then
            If Len(GetRelativePath) > 0 Then
              GetRelativePath = GetRelativePath & «..»
            Else
              GetRelativePath = GetRelativePath & «..»
            End If
          End If
          If Len(sToTmp) > 0 Then
            If Len(sTmp) > 0 Then
              sTmp = sTmp & «» & sToTmp
            Else
              sTmp = sTmp & sToTmp
            End If
          End If
        End If
  Loop
  If Len(sTmp) > 0 Then GetRelativePath = GetRelativePath & «» & sTmp
  If 0 = Len(GetRelativePath) Then GetRelativePath = «.»
End Function

 
Function GetLeftPart(sPath)
Dim i As Integer
  For i = 1 To Len(sPath)
    If «» = Mid(sPath, i, 1) Then
      GetLeftPart = Left(sPath, i — 1)
      Exit Function
    End If
  Next
  GetLeftPart = sPath
End Function

Public Sub InsertLinkToPicture()
Dim sFileName As String
Dim oField As Field
  Application.UndoRecord.StartCustomRecord

 
  With Application.FileDialog(msoFileDialogOpen)
    .Title = «Укажите рисунок»
    .AllowMultiSelect = False
    .ButtonName = «Select»
    .Filters.Clear
    .Filters.Add «Картинки», «*.jpg; *.tiff; *.tif; *.png»
    If sInitialPath = «» Then sInitialPath = Application.ActiveDocument.Path
    .InitialView = msoFileDialogViewList
    If .Show Then sFileName = .SelectedItems(1) Else Exit Sub
  End With

 
  If Left(Selection.Text, 1) <> Chr(13) Then
    Selection.TypeText Text:=vbCr
  End If
  sFileName = GetRelativePath(Application.ActiveDocument.FullName, sFileName)

 
  Select Case True
    Case Left(sFileName, 2) = «..»
      sFileName = Right(sFileName, Len(sFileName) — 2)
    Case Left(sFileName, 1) = «.»
      sFileName = Right(sFileName, Len(sFileName) — 1)
  End Select

 
  If Left(sFileName, 1) = «/» Or Left(sFileName, 1) = «» Then
    sFileName = Right(sFileName, Len(sFileName) — 1)
  End If

 
  Set oField = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldEmpty, _
  Text:=«INCLUDEPICTURE  « + Chr(34) + _
        Replace(sFileName, «», «/») + _
        Chr(34) + » d « _
        , PreserveFormatting:=True)

       
  If InStr(sFileName, «_35%») Then
    ActiveDocument.Hyperlinks.Add Anchor:=oField.Result, Address:=Replace(sFileName, «_35%», «»), SubAddress:=«»
  End If

 
  Selection.TypeText Text:=vbCrLf + Replace(sFileName, «_35%», «»)
  Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
  Selection.Font.Italic = True
  Selection.Font.Bold = True
  Selection.Font.Color = wdColorRed
  Selection.EndKey
  Selection.Collapse
  Selection.TypeParagraph
  Selection.Range.Style = ActiveDocument.Styles(wdStyleNormal)
  Application.UndoRecord.EndCustomRecord
End Sub

КостяФедореев

Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

1

Word

21.07.2020, 11:38. Показов 6707. Ответов 11

Метки word 2016 (Все метки)


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

Приветствую.
Как оказалось VBA Word не мое) Да и не охота осваивать, редко использую, но вот возникла необходимость вставить картинку в документ на все страницы в нужном положении и обтекание-перед текстом-
Что получилось наделать):

Visual Basic
1
2
3
4
5
6
7
8
9
Sub Picture()
Dim shpCanvas As Shape
Set shpCanvas = ActiveDocument.Shapes _
.AddCanvas(Left:=300, Top:=700, _
Width:=600, Height:=400)
shpCanvas.CanvasItems.AddPicture _
FileName:="C:UsersadminDesktop4234234234.jpg", _
LinkToFile:=False, SaveWithDocument:=True ' тут бы диалоговое окно для выбора файла картинки, думаю разберусь как
End Sub

теперь эту красоту надо на всех страницах разместить)
С циклом по страницам не знаком,
Подскажите пожалуйста.

Добавлено через 8 минут
И ещё есть ли возможность макрос сохранить файлом, чтоб в поле документа перетащить и он установится?



0



779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

21.07.2020, 11:48

2

картинка на всех страницах — это подложка что ли?



0



Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

21.07.2020, 11:53

 [ТС]

3

amd48, нет.
это картинка из файла, поверх текста в нужном месте, на всех листах.



0



779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

21.07.2020, 11:53

4

Цитата
Сообщение от КостяФедореев
Посмотреть сообщение

макрос сохранить файлом, чтоб в поле документа перетащить и он установится?

Поле документа — это что в ваших терминах? Если надо иметь макрос, который будет работать с разными документами, то можно разместить его в шаблоне Normal.dot и для него сделать кнопку. Или лучше сделать надстройку — это dot-шаблон в папке %appdata%MicrosoftWordSTARTUP



0



Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

21.07.2020, 11:55

 [ТС]

5

Подложку я умею делать, а тут именно картинка в определенной области

Добавлено через 1 минуту

Цитата
Сообщение от amd48
Посмотреть сообщение

Поле документа — это что в ваших терминах? Если надо иметь макрос, который будет работать с разными документами, то можно разместить его в шаблоне Normal.dot и для него сделать кнопку. Или лучше сделать надстройку — это dot-шаблон в папке %appdata%MicrosoftWordSTARTUP

Думаю это я и имел ввиду, только Вы корректно это описали))



0



amd48

779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

21.07.2020, 12:15

6

наверное, так:

Visual Basic
1
2
3
4
5
6
7
    Dim shpCanvas As Shape
    Dim i As Byte
    For i = 1 To ActiveDocument.Content.Information(wdActiveEndAdjustedPageNumber)
        Set shpCanvas = ActiveDocument.Shapes.AddCanvas(Left:=300, Top:=700, Width:=600, Height:=400)
        shpCanvas.CanvasItems.AddPicture FileName:="C:UsersadminDesktop4234234234.jpg"
        Selection.GoTo wdGoToPage, wdGoToNext, 1
    Next



0



КостяФедореев

Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

21.07.2020, 15:34

 [ТС]

7

amd48, Спасибо! Отлично работает!

Что-то не могу понять, как dot-шаблон сохранить?

Добавлено через 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
Sub Вертикально()
Dim shpCanvas As Shape
Dim i As Byte
Dim fd As FileDialog
Dim vrtSelectedItem As Variant
 
 Set fd = Application.FileDialog(msoFileDialogOpen)
  
With fd
  
    If .Show = -1 Then
 
        For Each vrtSelectedItem In .SelectedItems
            For i = 1 To ActiveDocument.Content.Information(wdActiveEndAdjustedPageNumber)
        Set shpCanvas = ActiveDocument.Shapes.AddCanvas(Left:=400, Top:=750, Width:=600, Height:=400)
            shpCanvas.CanvasItems.AddPicture FileName:=vrtSelectedItem
            Selection.GoTo wdGoToPage, wdGoToNext, 1
            Next
        Next vrtSelectedItem
    
    Else
    End If
End With
End Sub



0



779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

21.07.2020, 15:43

8

Цитата
Сообщение от КостяФедореев
Посмотреть сообщение

как dot-шаблон сохранить?

Сохранить как. Выбрать «шаблон». Ворд автоматически откроет для сохранения папку шаблонов. Но надо выбрать %appdata%MicrosoftWordSTARTUP
Желательно использовать формат 2003-го ворда, а не эти новые dotxи всё такое. В старых форматах макросы сохранялись без вопросов. В новых надо всегда выбирать формат именно с поддержкой макросов, иначе они не сохранятся. И всё программирование улетит в трубу



0



Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

21.07.2020, 15:48

 [ТС]

9

Цитата
Сообщение от amd48
Посмотреть сообщение

Сохранить как. Выбрать «шаблон».

А я потом смогу этот шаблон на другой комп перекинуть?



0



779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

21.07.2020, 17:54

10

Файл есть файл. Какие проблемы?



0



Часто онлайн

790 / 529 / 237

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

Сообщений: 1,820

21.07.2020, 19:14

 [ТС]

11

amd48, действительно, чёто затупил я

Добавлено через 1 минуту
amd48, а в надстройку это все запихать? Это особенный какой-то танец с бубном?
Или решаемо без особых усилий?



0



Lyutikova

1 / 1 / 0

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

Сообщений: 45

31.12.2021, 09:07

12

Доброго времени суток. Похожая ситуация) Есть отсканированные рукописные документы. Их сканы в PNG, в папке C:Scan имена файлов 1.png,2.png,3.png,4.png,5.png вставлять каждый файл на новую страницу. Вот так получается

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
Sub Scan()
'
' Scan Макрос
'
'
    Selection.WholeStory
    With ActiveDocument.Styles(wdStyleNormal).Font
        If .NameFarEast = .NameAscii Then
            .NameAscii = ""
        End If
        .NameFarEast = ""
    End With
    With ActiveDocument.PageSetup
        .LineNumbering.Active = False
        .Orientation = wdOrientPortrait
        .TopMargin = CentimetersToPoints(0)
        .BottomMargin = CentimetersToPoints(0)
        .LeftMargin = CentimetersToPoints(0)
        .RightMargin = CentimetersToPoints(0)
        .Gutter = CentimetersToPoints(0)
        .HeaderDistance = CentimetersToPoints(1.25)
        .FooterDistance = CentimetersToPoints(1.25)
        .PageWidth = CentimetersToPoints(21)
        .PageHeight = CentimetersToPoints(29.7)
        .FirstPageTray = wdPrinterDefaultBin
        .OtherPagesTray = wdPrinterDefaultBin
        .SectionStart = wdSectionNewPage
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .VerticalAlignment = wdAlignVerticalTop
        .SuppressEndnotes = False
        .MirrorMargins = False
        .TwoPagesOnOne = False
        .BookFoldPrinting = False
        .BookFoldRevPrinting = False
        .BookFoldPrintingSheets = 1
        .GutterPos = wdGutterPosLeft
    End With
    With Selection.ParagraphFormat
        .LeftIndent = CentimetersToPoints(0)
        .RightIndent = CentimetersToPoints(0)
        .SpaceBefore = 0
        .SpaceBeforeAuto = False
        .SpaceAfter = 0
        .SpaceAfterAuto = False
        .LineSpacingRule = wdLineSpace1pt5
        .Alignment = wdAlignParagraphJustify
        .WidowControl = True
        .KeepWithNext = False
        .KeepTogether = False
        .PageBreakBefore = False
        .NoLineNumber = False
        .Hyphenation = True
        .FirstLineIndent = CentimetersToPoints(0)
        .OutlineLevel = wdOutlineLevelBodyText
        .CharacterUnitLeftIndent = 0
        .CharacterUnitRightIndent = 0
        .CharacterUnitFirstLineIndent = 0
        .LineUnitBefore = 0
        .LineUnitAfter = 0
        .MirrorIndents = False
        .TextboxTightWrap = wdTightNone
        .CollapsedByDefault = False
    End With
    Selection.InlineShapes.AddPicture FileName:="C:Scan1.png", LinkToFile:= _
        False, SaveWithDocument:=True
    Selection.InsertBreak Type:=wdPageBreak
    Selection.InlineShapes.AddPicture FileName:="C:Scan2.png", LinkToFile:= _
        False, SaveWithDocument:=True
    Selection.InsertBreak Type:=wdPageBreak
    Selection.InlineShapes.AddPicture FileName:="C:Scan3.png", LinkToFile:= _
        False, SaveWithDocument:=True
    Selection.InsertBreak Type:=wdPageBreak
    Selection.InlineShapes.AddPicture FileName:="C:Scan4.png", LinkToFile:= _
        False, SaveWithDocument:=True
End Sub

Но вот можно ли как то вставить из папки Scan не по именам а выбрать все из папки и вставить в документ на каждую страницу одну картинку?

Добавлено через 27 минут
Вот результат https://disk.yandex.ru/i/nN52xb0ezOuCxg



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

31.12.2021, 09:07

Помогаю со студенческими работами здесь

Вставить картинки в определенные места документа в определенном размере
Добрый день,
подскажите, плз:
как с помощью макросов реализовать следующее:

word 2007
есть…

Как вставить текст в определенное место WORD документа?
Подскажите пожалуйста, как вставить программно в вордовский документ текст в определенное место и…

Вставить нумерацию в таблицу нижнего колонтитула документа word
Подскажите, пожалуйста, почему нельзя напрямую в ячейку таблицы колонтитула документа word вставить…

Как считать текст, таблицы и картинки из документа word
Как считать текст, таблицы и картинки из документа word? И наоборот записать в него. Попытался сам,…

Макрос Word: вставить в конец документа строчку с информацией о документе
Нужен макрос, вставляющий в конец документа строчку с информацией о документе (путь, имя, дата…

На оборотной стороне документа word в правой части документа, текст съезжает за границу документа
Добрый вечер.

Есть код, который формирует документ из шаблона. И все вроде бы, но происходит что…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

12

Понравилась статья? Поделить с друзьями:
  • Vba word вставка закладки
  • Vba word вставить формулу
  • Vba word вставить текст после курсора
  • Vba word вставить текст в определенное место
  • Vba word вставить текст в конец документа