1. Открыть файл Excel в который необходимо добавить макрос
2. Нажать комбинацию клавиш alt+f11
3. В открывшемся окне вверху слева сделайте двойной клик по «Эта книга»

4. Справа откроется окно для ввода текста
5. Вставьте в него следующий текст:
Кликните здесь для просмотра всего текста
| 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
| Sub CreateWordFile()
Dim filePath As String
Dim data As Collection
Dim headersRow As Integer
headersRow = 1
filePath = SelectWordTemplate()
If filePath <> "" Then
Set data = GetSelectedData(headersRow)
Call CreateAndFillWordDocument(filePath, data)
End If
End Sub
Function SelectWordTemplate() As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Title = "Select a Word Template"
.Filters.Add "Word Files", "*.dotx;*.docx;*.docb;*.doc", 1
.AllowMultiSelect = False
If .Show = True Then
SelectWordTemplate = fd.SelectedItems(1)
End If
End With
End Function
Function GetSelectedData(headerRowIndex As Integer) As Collection
Set GetSelectedData = New Collection
Dim cell As Range
Dim cellValue As String
Dim cellKey As String
Dim emptyCellCounter As Integer
emptyCellCounter = 0
For Each cell In Selection
cellValue = cell.Value2
cellKey = cell.Worksheet.Cells(headerRowIndex, cell.Column).Value2
GetSelectedData.Add Array(cellKey, cellValue)
If cellValue = "" Then
emptyCellCounter = emptyCellCounter + 1
Else
emptyCellCounter = 0
End If
If emptyCellCounter > 100 Then
Exit Function
End If
Next cell
End Function
Sub CreateAndFillWordDocument(file As String, data As Collection)
Set wApp = CreateObject("Word.Application")
wApp.DisplayAlerts = False
Dim wDoc As Object
Set wDoc = wApp.Documents.Add(Template:=file, NewTemplate:=False, DocumentType:=0)
Call FillWordDocument(wDoc, data)
wApp.DisplayAlerts = True
wApp.Visible = True
End Sub
Sub FillWordDocument(wDoc As Object, data As Collection)
Dim key As Variant
For i = 1 To data.count
Dim text As String
Dim replace As String
Dim content As String
text = "{%" & data.Item(i)(0) & "%}"
replace = data.Item(i)(1)
Set myRange = wDoc.content
myRange.Find.Execute FindText:=text, ReplaceWith:=replace
Next i
End Sub |
|
6. Нажмите «посмотреть в Excel»

7. Откроется Excel с вашим файлом. Нажмите сохранить как.
8.Выберите тип фала «Книга Excel с поддержкой макросов (*.xlsm) и нажмите сохранить.

Макрос установлен.