Import project to excel

The Export Wizard and Import Wizard help you transfer project data between Microsoft Project and other programs. The following is a list of formats you export to or import from.

  • Microsoft Excel (as a workbook or PivotTable report)

  • text-only (tab delimited)

  • comma-separated values (CSV)

  • Extensible Markup Language (XML)

By defining or editing the export or import maps of these wizards, you can easily transfer data to and from the task, resource, or assignment fields that you want.

What do you want to do?

  • Export project information

  • Import project information

Export project information

  1. Choose File > Save As.

  2. Choose Browse. (Not applicable in Project 2010.)

  3. In the Save As type box, select the file format that you want to export data to.

  4. In the File name box, type a name for the exported file.

  5. Choose Save.

  6. Follow the instructions in the Export Wizard to export the data that you want into the proper fields of the destination file.

  7. When the wizard prompts you to create a new map or use an existing one, do one of the following:

    • Choose New map to create a new export map from scratch.

    • Choose Use existing map to use a default map or a map that you previously defined and saved.

  8. On the Task Mapping, Resource Mapping, or Assignment Mapping page of the Export Wizard, verify or edit the mapping assumptions of Project, or create a new map:

    • To export specific project information, type or select the field that you want in the From column, and then press ENTER.

    • To add all task, resource, or assignment fields in your project to the export map, choose Add All.

    • To add all task or resource fields of a specific table to the export map, choose Base on Table. Select the table you want to use, and then select OK.

    • To remove all task, resource, or assignment fields from an export map, choose Clear All.

    • To insert a new field above another field, select a field in the From column, and then choose Insert Row.

    • To insert a new field above another field, select a field in the From column, and then choose Insert Row.

    • To delete a field, select it in the From column, and then choose Delete Row. To change the name of the field in the destination file, select the field in the To column, and then type a new name.

  9. To export certain tasks or resources only, select the filter that you want in the Export filter box.

  10. If you want to change the order of the fields in the destination file, select a field in the To column, and then use the Move buttons to move the field to the position that you want.

  11. On the last page of the Export Wizard, choose Finish to export your data.

Notes: 

  • You can export only an entire project to XML format. Project maps the data automatically, without the Export Wizard. Also, to minimize the file size, fields that contain null values are not included in the exported XML file.

  • On the Task Mapping, Resource Mapping, or Assignment Mapping page of the Export Wizard, under Preview, you can review the layout of the export map.

  • You can save a new or edited export map if you want to use it again. On the last page of the Export Wizard, choose Save Map, and then type a name in the Map name box. The new map will be added to the list of predefined maps.

  • You can use an existing export map from another project if the map is available in the global file. By using the Organizer, you can copy an export map from a project file to the global file.

  • When you create an export map to save data to either CSV file format or TXT file format and you set the text delimiter, the delimiter, not the file extension, controls the file type. For example, if you save to a file named Myproject.csv but you specified a tab delimiter in the map, the CSV file will have tabs instead of commas, even though the file extension indicates commas.

Import project information

You can import information into Project by using any entered field from another product’s file format, such as Microsoft Office Excel, Microsoft Office Access, Extensible Markup Language (XML), comma-separated values (CSV), or tab delimited text format.

  1. Choose File > Open > Browse.

    (In Project 2010, choose File > Open.)

  2. In the Files of type box, select the file type that you want to import data from.

  3. Navigate to the folder that contains the file you want to import, and then select the file in the file list.

  4. Choose Open.

  5. Follow the instructions in the Import Wizard to import the data that you want into the proper Project fields.

  6. On the Task Mapping, Resource Mapping, or Assignment Mapping page of the Import Wizard, verify or edit the mapping assumptions of Project:

    • To import the data from a field in the source file to a different Project field, select the field in the To column, select a new field, and then press ENTER.

    • To change the name of a field in the destination file, select the field in the To column, and then type a new name.

    • To delete a field, select it in the From column, and then choose Delete Row.

    • To insert a new field above another field, select a field in the From column, and then choose Insert Row.

    • To remove all task, resource, or assignment fields from an import map, choose Clear All.

    • To add all task, resource, or assignment fields of the destination file to the import map, choose Add All.

      Tip: On the Task Mapping, Resource Mapping, or Assignment Mapping page of the Import Wizard, under Preview, you can preview the layout of the import map.

  7. To change the order of the fields in the destination file, select a field in the To column, and then use the Move buttons to move the field to the position that you want.

  8. On the last page of the Import Wizard, choose Finish to import your data.

    Tip: You can save a new or edited import map if you want to use it again. On the last page of the Import Wizard, choose Save Map, and then type a name in the Map name box. The new map will be added to the list of predefined maps.

Notes: 

  • You can use an existing import map from another project if the map is available in the global file. By using the Organizer, you can copy an import map from a project file to the global file.

  • When you create an import map to incorporate data from either CSV file format or TXT file format and you set the text delimiter, the delimiter, not the file extension, controls the file type. For example, if you import a file named Myproject.csv but you specified a tab delimiter in the map, the CSV file will have tabs instead of commas, even though the file extension indicates commas.

  • Although you can enter values in some calculated fields, Project may recalculate these values, either automatically or when you specify.

  • Project can import only XML data that can be validated against its data interchange schema.

  • If you are using Microsoft Project Professional, and you want to import information from another file format into an enterprise project that requires you to enter specific information for tasks, you won’t be able to save the project until you enter all required information.

  • If you are using Microsoft Project Professional, remember that resource cost fields cannot be updated in an enterprise project. You can import resource cost information only in nonenterprise projects or for nonenterprise resources in a project.

Любую таблицу из MS Project можно экспортировать в MS Excel. Для этого надо сначала установить настройку безопасности, позволяющую открывать и сохранять в программе файлы других форматов.

Для экспорта надо настроить существующую таблицу или, что предпочтительней, создать новую таблицу, если данные регулярно будут отправляться в MS Excel.

Далее следует  выбрать команду Файл – Сохранить как. В окне сохранения документа изменить тип файла на Книга Excel, указать место для сохранения файла (диск, папку), имя файла и нажать кнопку Сохранить.

Экспорт в MS Excel из MS Project

В окне Мастер экспорта нажать кнопку Далее, на следующем шаге оставить вариант по умолчанию Выбранные данные  и снова нажать кнопку Далее.

При первом случае экспорта на шаге Схема оставляем вариант Создать новую схему, при повторной аналогичной выгрузке – Использовать существующую схему

Экспорт в MS Excel из MS Project

На шаге Параметры схемы выбираем данные для выгрузки, определяем, нужно ли в Excel выгружать заголовки столбцов, в случае выгрузки задач – надо ли выгружать и назначения, и нажать Далее

Экспорт в MS Excel из MS Project

Самый важный шаг – Сопоставление. В зависимости от флажков на предыдущем шаге сопоставление надо будет сделать для задач, ресурсов и назначений. На этом шаге мы укажем название листа книги Excel для таблицы с выгруженными данными, фильтр выгрузки.

В таблице на этом шаге можно по одному определить столбцы таблиц Project  для выгрузки, для столбца задать новое название для Excel. А можно, нажав кнопку На основе таблицы, выбрать готовую таблицу Project целиком. Лишние столбцы можно удалить кнопкой Удалить строку.

Экспорт в MS Excel из MS Project

Кнопкой Далее переходим на шаг Конец определения схемы, на котором можно сохранить схему для последующего использования (кнопка Сохранить схему) и нажать Готово.

В результате этого алгоритма в заданной папке появится файл Excel с выгруженными данными. В случае выгрузки и задач, и ресурсов, и назначений они будут размещаться на разных листах книги Excel.

Microsoft Project is an effective management service for budgeting, tracking and analyzing project tasks. It stores data in tables whose contents you can easily migrate into Excel workbooks. Project saves its files directly as Excel workbooks, and its Export wizard customizes the transition by assigning Excel fields for each Project data column. Excel can then chart the data, perform spreadsheets functions on it, sort it or run Visual Basic macros on it.

  1. Click «File» in the Project ribbon and select «Save As.»

  2. Click the «Save as type» drop-down box and select «Excel Workbook.»

  3. Click «Save» to open the Project Export wizard. Click «Next.»

  4. Click the «Selected Data» option button. Click «Next.»

  5. Click the «New Map» option button. Click «Next» to open a screen listing three types of tables that Excel can import: «Tasks,» «Resources» and «Assignments.»

  6. Check the boxes beside each type of table that you want Excel to import. Click «Next.»

  7. Click the cells in the «From: Microsoft Office Project Field» column and type the names of fields that Excel must import.

  8. Click the cells in the «To: Excel Field» column and type destination field headings.

  9. Click «Next.» If you selected more than one table in Step 6, a new mapping screen open. Repeat Steps 7 and 8 with this screen. Otherwise, the wizard’s final screen opens.

  10. Click «Finish.»

  11. Open the new Excel workbook with Microsoft Excel.

How to import Microsoft Project files into Microsoft Excel

mpp_to_xls Have you ever managed a larger project with several subprojects, hundreds of tasks and milestones, dozens of members in the project team and even more other staff contributing to the project, spread all over almost every department of the company? If so, you might have used Microsoft Project to plan and monitor the project.

Since there were so many different people contributing, you may have encountered the following challenge: You had to distribute the actual project plan to all team members at least once a week, but not everyone had Microsoft Project installed on his computer. So you couldn’t simply send the Microsoft Project file.

Sounds familiar? What do you usually do?

You copy the project plan as a picture and paste it into a PowerPoint file? I don’t think so. If it is a really big project, I bet you tried this only once.

You create a PDF? Well, this looks better, but still needs some PDF-creating software installed on your computer. Even if you have a PDF-creator, PDFs are quite inflexible.

This is still a workaround, but wouldn’t it be better to provide a copy of the project plan in Microsoft Excel? Usually everyone has Excel installed on his computer. And the team members would be able to copy and paste tasks and other data, to do their own side calculations, to filter the project plan, to define the print area and so forth.

We need a little tool for importing Microsoft Project Files into Excel with ease.

Of course Microsoft Project provides a built-in function to export data from a MPP-file to Microsoft Excel by clicking “Save As” and selecting “Microsoft Excel Workbook”.

The result usually looks like this:

Project Standard Export - click to enlarge

Compelling? Not really. A starting point, but it would still be a long tramp to transfer this into something useful like this one:

Project Plan xls - click to enlarge

Project plan example taken from Microsoft’s Office Online Website (project management plan)

Looks better, doesn’t it? And yes, this is Excel.

What if you could produce this with only a couple of clicks?

Well, here is a way to do this:

The used Excel functions and features:

  • A few named ranges

  • Conditional formatting to highlight the first three PSP-levels in different shades of grey

  • MIN function to calculated the project start date

  • ROUNDDOWN function to round start and end dates to full days
    (used in the hidden columns L and M)

  • Conditional formatting to create the pseudo Gantt chart
    (black fill color for tasks, orange fill color for milestones)

Advanced Excel features, but no rocket science.

Additionally there is – of course — some VBA code managing the automatic import from Microsoft Project. But even this is only 90 lines of code, including a nice progress indicator I “borrowed” from John Walkenbach’s brilliant website. Thanks John!

The VBA code (started when clicking on the worksheet button) is not too complicated. Here is what it does:

  • Let the user select the project file to import (in a standard open-file-dialog)

  • Delete all exiting data in the Excel file

  • Open the Microsoft Project application (if installed)

  • Loop through all the tasks of the Project file and write the defined information to the Excel worksheet

  • Close the Microsoft Project application

For anyone who is interested in the code in detail: the workbook provided for download is without password protection. If you want to, go and figure it out.

A short summary

The advantages

  • Import Microsoft Project files into Excel with a couple of mouse clicks

  • Display your complete project plan in a professional Excel template without any further effort on formatting, etc.

  • Provide all your project team members with the actual project plan in Excel and enable them to do more than just print

The shortfalls

  • The tool uses a hardcoded structure of imported project columns (WBS, task name, duration, start, end, predecessor, successor, resource initials). If you want to change this, you will have to change the VBA code and – in case you need additional columns – also the structure of the workbook

  • It is a one-way street: if anyone changes the project plan in Excel, you would have to manually update the Microsoft Project file

  • The file for download is restricted to 150 tasks and 200 days. You can easily change that by inserting the number of required rows and columns somewhere in the middle of the existing table and copying down and right the formulas and formats from above and left

The tool for free download:

Download Import MPP into XLS (Excel 97 – 2003, 152.5K)

The tool has been tested with Excel 2003/2007 and Microsoft Project 2003. You need to have Microsoft Project installed to run the macro.

Список курсов/Материалы темы «Управление интеграцией»

Видео материала «Экспорт данных с MS Project Pro в MS Excel»

Ниже приведенная информация является справочным материалом. Подробнее о данном материале и его практическом применении вы можете узнать, просмотрев видео.


Содержание:

  1. Экспорт данных с MS Project Pro в MS Excel

Экспорт данных с MS Project Pro в MS Excel

MS Project Pro позволяет экспортировать данные в MS Excel. Для экспорта данных:

1. Перейдите в пункт меню «Файл» пункт «Экспорт«.

2. Выбрать пунтк «Сохранть проект как файл» и выбрать формат после чего нажать на кнопку «Сохранить«.

Экспорт данных с MS Project Pro в MS Excel

3. Выбрать место на диске куда записать экспортируем файл.

4. Выбрать тип экспорта. Вы можете выбрать стандартный экспорт это пункт «Шаблон проекта (Excel)«. Для выбора данных для экспорта — пункт «Выбранные данные«.

5. Далее Вы можете создасть или выбрать схему экспорта. Для выбора существующих схем выберите пункт «Использовать существующую схему«. Или создасть новую схему выбрав пункт «Создать новыую схему«. 

6. Выберите схему и нажмите на кнопку «Далее«

Экспорт данных с MS Project в MS Excel

7. Выберите тип данны MS Project Pro это могут быть: задачи, ресурсы или назначения. Кроме этого можете выбрать экспорт заголовок и обязательная выбрузка назначений. Для этого установите соотвествующие пункты.

9. Укажите название закладки в странице MS Excel. Если нужно выберите фильтер MS Project Pro для выбранных данных. Укажите в какие поля MS Excel выгружать поля MS Project Pro. Вы можете выгрузить данные с уже существующей таблицы (кнопка «На основе таблицы…«).

10. Нажмите на кнопку «Готово«.

Экспорт данных с MS Project Professional в MS Excel

Вас могут заинтересовать следующие материалы

Календарь проекта в MS Project Pro
Установка и настройка календарей проектов и календарей системы.

01.11.2022

15767

Корпоративные календари в MS Project Online
Установка и настройка календарей проектов и календарей системы

20.05.2020

1749

Дополнительные параметры сервера MS Project Online
Описание особенностей настройки системы управления проектами MS Project Online

20.05.2020

1295

Сделал импорт-экспорт, но сократил количество полей до стандартного набора, который появляется при создании нового проекта:
1. «Название задачи»
2. «Длительность»
3. «Начало»
4. «Окончание»
5. «Предшественники»
6. «Последователи»
7. «Название ресурсов»

Выкладываю для тех, кто, возможно, столкнется с подобным.

Все макросы написаны для Экселя и запускаются из него. Для импорта проекта в эксель необходимо откруть его в проджекте. Макрос импортирует все открытые проекты на разные листы Экселя:

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
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
120
121
122
123
124
125
126
127
128
129
130
Sub ImportProjectTasks(proj, xlbook As Workbook) ' импорт проекта Proj
 
Dim xlApp As Application
 
Dim xlSheet As Worksheet
 
Dim t ' As Task
Dim Asgn ' As Assignment
Dim ColumnCount As Integer
Dim Columns As Integer
Dim Tcount As Integer
Dim res As String
Dim xlRow As Range
Dim xlCol As Range
Dim sname As String
Dim s As String
Dim i As Integer
 
 
Set xlSheet = xlbook.Worksheets.Add
sname = "Импорт проекта"
If Check_sheet_name(sname, xlbook) = True Then 'если такое имя уже есть, то ищем свободные варианты
    i = 0
    Do
    i = i + 1
    s = sname & "(" & CStr(i) & ")"
    Loop While Check_sheet_name(s, xlbook) = True
    
    sname = s
End If
 
xlSheet.Name = sname 'ActiveProject.Name
'count columns needed
ColumnCount = 0
For Each t In proj.Tasks
    If Not t Is Nothing Then
        If t.OutlineLevel > ColumnCount Then
            ColumnCount = t.OutlineLevel
        End If
    End If
Next t
 
'write header info about whole project
Set xlRow = xlSheet.Range("A1")
xlRow.Value = "Имя файла:"
xlRow.Offset(0, 1).Value = proj.Name
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Имя проекта: "
xlRow.Offset(0, 1).Value = proj.Title
 
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Начало проекта:"
xlRow.Offset(0, 1).Value = proj.Start
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Окончание проекта:"
xlRow.Offset(0, 1).Value = proj.Finish
 
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Уровень вложенности задач" '
Set xlRow = xlRow.Offset(1, 0)
 
'label Columns
For Columns = 1 To (ColumnCount + 1)
    Set xlCol = xlRow.Offset(0, Columns - 1)
    xlCol.Value = Columns - 1
Next Columns
 
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "ID"
 
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Длительность, дн."
 
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Дата начала"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Дата окончания"
 
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Предшественник"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Последователь"
 
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Названия ресурсов"
 
'Set xlCol = xlCol.Offset(0, 1)
'xlCol.Value = "Текущее выполнение, дн." '"actual work"
 
'write tasks info
Tcount = 0
For Each t In proj.Tasks
    If Not t Is Nothing Then
        Set xlRow = xlRow.Offset(1, 0)
        Set xlCol = xlRow.Offset(0, t.OutlineLevel)
        xlCol.Value = t.Name
        Set xlCol = xlRow.Offset(0, ColumnCount + 1)
        xlCol.Value = t.ID
        
        
        Set xlCol = xlCol.Offset(0, 1)
        xlCol.Value = t.Duration / 480
        
        Set xlCol = xlCol.Offset(0, 1)
        xlCol.Value = t.Start 'Text
        Set xlCol = xlCol.Offset(0, 1)
        xlCol.Value = t.Finish 'Text
        
        Set xlCol = xlCol.Offset(0, 1)
        xlCol.Value = t.Predecessors
        Set xlCol = xlCol.Offset(0, 1)
        xlCol.Value = t.Successors
        
        If t.Summary Then
            xlSheet.Rows(xlCol.Row).Font.Bold = True
        End If
        'cumulate resource info in 1 line
        res = ""
        For Each Asgn In t.Assignments
            res = res + Asgn.ResourceName + ";"
        Next Asgn
        
        Set xlCol = xlCol.Offset(0, 1)
        xlCol.Value = res
        
        Tcount = Tcount + 1
    End If
Next t
 
End Sub

Экспорт информации в Проджект с активного листа. Структура данных должна соответствовать импортируемой информации. При необходимости изменения уровня вложенности, нужно добавлять столбцы перед ID. Чем ближе к столбцу ID, тем ниже уровень вложенности(уровень 0 не заполняется).

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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
Sub exportToProject()
 
Dim PrApp As MSProject.Application
Dim proj As Project
Dim xlbook As Workbook
Dim t As Task
Dim xlSheet As Worksheet
Dim Asgn As Assignment
Dim ColumnCount As Integer
Dim Columns As Integer
Dim Tcount As Integer 'счетчик задач
Dim res As String
Dim xlRow As Range
Dim xlCol As Range
Dim r As Range
Dim sname As String
Dim s As String
Dim i As Integer
Dim idCol As Integer
 
Set xlSheet = ActiveWorkbook.ActiveSheet
'Находим параметр ID
Set xlRow = xlSheet.Range("A6")
Set xlCol = xlRow
While UCase(xlCol.Text) <> "ID"
    Set xlCol = xlCol.Offset(0, 1)
    If (xlCol.Column > 5000) Then 'защита от дурака. завершаем после 5000 просмотренных столбцов
        MsgBox "Формат файла не соответствует эталону.В 6 строке не найден параметр ID."
        Exit Sub
    End If
Wend
idCol = xlCol.Column
If idCol < 2 Then
    MsgBox "Формат файла не соответствует эталону. Отсутствуют уровни структуры"
    Exit Sub
End If
' проверяем открытые приложения
Set PrApp = CreateObject("MSProject.Application")
PrApp.Visible = True
Set proj = PrApp.Projects.Add
'выставляем автоматическое планирование
proj.NewTasksCreatedAsManual = False
'вводим основные параметры проекта
Call inputMainParameters(xlSheet, proj)
'запускаем основной цикл переноса данных
Dim taskFlag As Boolean ' флаг наличия названия задачи
Dim taskName As Range ' ячейка с названием задачи
Set xlRow = xlSheet.Range("A7")
Tcount = 0
While xlRow.Offset(0, idCol - 1).Value <> ""
    taskFlag = False
    For i = 1 To idCol - 1
        If Trim(xlRow.Offset(0, i - 1).Value) <> "" Then
            Set taskName = xlRow.Offset(0, i - 1)
            taskFlag = True
        End If
    Next i
    If taskFlag = False Then
        MsgBox "Отсутствует название задания. Строка: " & CStr(taskName.Column)
        Exit Sub
    End If
    Set t = proj.Tasks.Add(taskName.Value)
    t.OutlineLevel = taskName.Column - 1
    Set xlRow = xlRow.Offset(1, 0)
Wend
Set xlRow = xlSheet.Range("A7")
'записываем параметры задач(так сделано чтобы нормально вписывались последователи и предшественники)
Tcount = proj.Tasks.Count
For i = 1 To proj.Tasks.Count
    Set t = proj.Tasks(i)
    Set xlCol = xlRow.Offset(0, idCol)
    Call inputTaskParameters(xlCol, t, proj)
    Set xlRow = xlRow.Offset(1, 0)
    PrApp.TaskOnTimeline (t.ID)
Next i
 
Excel.Application.Visible = True
PrApp.ZoomTimescale Entire:=True
Set proj = Nothing
Set t = Nothing
Set PrApp = Nothing
MsgBox ("Экспорт данных завершен. Задач создано: " & Tcount)
End Sub
 
Function inputParameter(c As Range, par As Object, Optional flag As Boolean = False) As Boolean ' функция пишет параметр, если ячейка с не пустая
If Trim(c.Value) <> "" Then
    par = c.Value
    If (flag = True) Then
        par = c.Value * 480
    End If
    inputParameter = True
Else
    inputParameter = False
End If
End Function
 
Function addResources(ByRef t, r As Range, proj) As Boolean  'считываем ячейку с названием ресурсов, разделяем ресурсы и добавляем их
Dim s As String
Dim resarr ' массив ресурсов
Dim res 'As String 'элемент массива
Dim i As Integer
Dim e As Integer
Dim b As Integer
Dim resObj
Dim resID As Integer 'ИД ресурса
 
If Trim(r.Value) = "" Then
    addResources = False
Else
    s = r.Value
    resarr = Split(s, ";")
    'вычисляем размерность массива
    If (LBound(resarr) = 0) Then ' начало массива
        b = -1
    Else
        b = LBound(resarr)
    End If
    e = UBound(resarr) ' конец массива
    For Each res In resarr
        res = Trim(res)
        If res <> "" Then
            If checkResources(proj.Resources, res) = False Then 'проверяем наличие ресурсов с таким именем, если нет, то добавляем в ресурсы проекта
                proj.Resources.Add (res)
            End If
            resID = findResIdByName(proj.Resources, res)
            If resID < 0 Then ' такого быть не должно, но все же
                addResources = False
                Exit Function
            End If
            t.Assignments.Add t.ID, resID, 1  'добавляем ресурс в проект со 100% использованием
        End If
    Next res
    addResources = True
End If
End Function
Sub inputMainParameters(ByVal whs As Worksheet, ByRef proj) 'вводим основные параметры проекта
Dim r As Range
 
'вводим основные параметры проекта
Set r = whs.Range("B2")
If Trim(r.Value) <> "" Then
    proj.Title = r.Value
End If
 
End Sub
 
Sub inputTaskParameters(ByVal cr As Range, ByRef t, ByRef proj) ' записываем параметры задачи
Dim dur As Boolean 'флаг показывает, установлен параметр длительности или нет
Dim r As Range
Set r = cr
 
 
dur = False
If (Trim(r.Value) <> 0) And (Trim(r.Value) <> "") Then
    t.DurationText = r.Value ' * 480' так правильнее преобразовывается
    dur = True
End If
Set r = r.Offset(0, 1)
If Trim(r.Value) <> "" Then
    t.StartText = r.Value
End If
Set r = r.Offset(0, 1)
If (Trim(r.Value) <> 0) And (Trim(r.Value) <> "") And (dur = False) Then ' пишем этот параметр только если длительность не заполнена(т.к. он высчитывается по старту проекта и длительности)
    t.StartText = r.Value
End If
Set r = r.Offset(0, 1)
If Trim(r.Value) <> "" Then
   t.Predecessors = r.Value
End If
Set r = r.Offset(0, 1)
If Trim(r.Value) <> "" Then
   t.Successors = r.Value
End If
 
Set r = r.Offset(0, 1)
Call addResources(t, r, proj)
    
End Sub
 
Function checkResources(res, n) As Boolean ' проверяет наличие ресурсов
Dim r
For Each r In res
    If r.Name = n Then
        checkResources = True
        Exit Function
    End If
Next r
checkResources = False
End Function
 
Function findResIdByName(res, n) As Integer  ' находит ИД ресурса по имени(отрицательное значение, если не нашел)
Dim r
For Each r In res
    If r.Name = n Then
        findResIdByName = r.ID
        Exit Function
    End If
Next r
findResIdByName = -1
End Function

Создание шаблона для проекта на активном листе:

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
Sub CreateFormForProject() 'создаем макет листа для экспорта в проджект
 
Dim wsh As Worksheet
Dim xlRow As Range
Dim xlCol As Range
 
Set wsh = ActiveSheet
 
Set xlRow = wsh.Range("A1")
xlRow.Value = "Имя файла:"
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Имя проекта: "
 
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Начало проекта:"
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Окончание проекта:"
 
Set xlRow = xlRow.Offset(1, 0)
xlRow.Value = "Уровень вложенности задач" '
Set xlRow = xlRow.Offset(1, 0)
'рисуем шапку таблицы
Set xlCol = xlRow
xlCol.Value = "0"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "1"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "ID"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Длительность, дн."
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Дата начала"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Дата Окончания"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Предшественник"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Последователь"
Set xlCol = xlCol.Offset(0, 1)
xlCol.Value = "Названия ресурсов"
 
MsgBox "Шаблон проекта готов"
End Sub

Можно назначить макросы на кнопки, кнопки поместить на ленту, а надстройку поместить в общедоступную сетевую папку, что позволит централизованно распространить макросы и вносить изменения.



0



Понравилась статья? Поделить с друзьями:
  • Import pdf file to word document
  • Import pandas as pd excel
  • Import options in excel
  • Import option in excel
  • Import in excel from pdf