Excel VBA - create column names using MS Project headers - excel

I'm in the middle of writing a script that populates an excel spreadsheet with data from an MS Project file. I would like the script to recognize the title name of the MS Project columns as I have a number of custom columns with different names (custom number fields are populated with different names)
The code below was my attempt, but i'm getting an error when it comes to writing the value of the task column title to the sheet, am I doing something wrong here?
Sub PopulateSheet()
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
Dim t As MSProject.Task
Dim xl as workbook
Dim s as worksheet
Dim Newsheet as worksheet
Set Xl = ThisWorkbook
BookNam = Xl.Name
Set Newsheet = Xl.Worksheets.Add
'Code to find and open project files
Set Proj = New MSProject.Application
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
MsgBox ("You Havent Selected a File")
Exit Sub
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
Newsheet.Name = NewProjFileName
Set s = Newsheet
'Populate spreadsheet header row with column titles from MS Project
s.Range("A1").Value = t.Number1 ***<-- Error '91' - Object variable or With block variable not set***
End Sub

Here is generic code that loops through the fields in the active task table and prints out the field headings as displayed in the table.
Sub GetTaskTableHeaders()
Dim t As Table
Set t = ActiveProject.TaskTables(ActiveProject.CurrentTable)
Dim f As TableField
For Each f In t.TableFields
If f.Field > 0 Then
Dim header As String
Dim custom As String
custom = Application.CustomFieldGetName(f.Field)
If Len(f.Title) > 0 Then
header = f.Title
ElseIf Len(custom) > 0 Then
header = custom
Else
header = Application.FieldConstantToFieldName(f.Field)
End If
Debug.Print "Field " & f.Index, header
End If
Next f
End Sub
Note that fields can be customized at the project level to be given a different title, or they can be customized at the table level. This code looks for both customizations and if neither is found, the field name is used.

Try the code below, explanation inside the code's comments:
Option Explicit
Sub PopulateSheet()
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
Dim PjTableField As MSProject.TableField ' New Object
Dim PjTaskTable As MSProject.Table ' New Object
Dim t As MSProject.task
Dim xl As Workbook
Dim s As Worksheet
Dim Newsheet As Worksheet
Dim BookName As String
Dim FileOpenType
Dim NewProjFilePath As String, NewProjFileName As String
Set xl = ThisWorkbook
BookName = xl.Name
Set Newsheet = xl.Worksheets.Add
'Code to find and open project files
Set Proj = New MSProject.Application
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
MsgBox ("You Havent Selected a File")
Exit Sub
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
Newsheet.Name = NewProjFileName
Set s = Newsheet
' Open MS-Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
Set NewProj = Proj.ActiveProject
' ===== New code Section =====
' set the Table object
Set PjTaskTable = NewProj.TaskTables(NewProj.CurrentTable)
' loop through all tablefields in table
For Each PjTableField In PjTaskTable.TableFields
If PjTableField.Field = pjTaskNumber1 Then ' check if currect field numeric value equals the numeric value of "Number1"
'Populate spreadsheet header row with column titles from MS Project
s.Range("A1").Value = PjTableField.Title ' populate "A1" with the field's title and
End If
Next PjTableField
End Sub

Related

Pull particular Excel cell value into Word document using Word VBA

I am new to VBA and macros.
I got the repeated task of copy data from Excel and paste it in a particular location in the word document.
For example, my excel sheet has the data like this:
Col1
Col2
ID_1
I'm_One
ID_2
I'm_Two
ID_3
I'm_Three
Now i'm looking for a Word macro
Get text in Word table with cell position 3
Find the same text in Excel Col1
Get the value of Col2 from Excel
Paste the value of Col2 in word table with cell position 10
Repeat the same process for another table in Word document
[Update]
I have tried with multiple code snippets by google search but unable to construct the working macro.
Sub pull_from_Excel2()
'ref: https://www.macworld.com/article/211753/excelwordvisualbasic.html
Dim Month As String
ID_Range = "A2:A6" 'Select this as range like "A2:A16"
Offset_to_fetch = 1 'Select this to fetch comments etc. value starts with
Set xlSheet = GetObject("D:\Excel.xlsx")
'Snippets:
'Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range("A3:A5").Value)
'8204
Dim Cell As Range, rng As Range
Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range(ID_Range).Value2)
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
For Each Cell In rng
Debug.Print Cell.Text
Next Cell
End Sub
I used this url to construct my skeleton code: https://www.macworld.com/article/211753/excelwordvisualbasic.html
When i try to get the values from the range of cells in excel, i got the following error for the code.
Set rng = xlSheet.Worksheets(1).Range(ID_Range).Value2
The above line gives "Object required" error when running.
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
The above line gives "Type Mismatch" error when running.
Notes: For this error, I tried to use for each loop as this is array but the error is showing before executing the for loop.
Kindly assist.
I recommend to use Option Explicit and declare all your varibales properly. This way it is less likely that you end up with unseen errors.
To activate it for all new codes that you add in the future, you can activate it directly in Excel and Word. This is a good practice and will protect you from doing it wrong by notifying you of not declared variables:
In the VBA editor go to Tools › Options › Require Variable Declaration.
This will add Option Explicit to new modules only. In existing modules Option Explicit needs to be added manually as first line.
Further I highly recommend to name your variables according what they contain because otherwise it gets very confusing. You named your variable xlSheet but you load a workbook into it and not a worksheet.
The next issue is that your code is in Word and if you declare rng As Range then this is of type Word.Range and not Excel.Range and those are diffetent types so that is why you get a "Type Mismatch" error.
To solve this you either go in Word VBA to Extras › Refereces … and set a reference to the Excel library so you can declare your variable Dim xlRng As Excel.Range or if you don't set a reference you declare it as Object or Variant like in below example:
' This code is in Word!
Option Explicit
Public Sub pull_from_Excel2()
'declare constants
Const ID_Range As Sting = "A2:A6" 'Select this as range like "A2:A16"
Const Offset_to_fetch As Long = 1 'Select this to fetch comments etc. value starts with
Dim xlWorkbook As Object
Set xlWorkbook = GetObject("D:\Excel.xlsx") 'This expects the Excel to be already open! If not open you need to use CreateObject("Excel.Application")
Dim xlRng As Object
Set xlRng = xlWorkbook.Worksheets(1).Range(ID_Range)
Dim xlCell As Object
For Each xlCell In xlRng
Debug.Print xlCell.Text
Next xlCell
End Sub
Note if your workbook Set xlWorkbook = GetObject("D:\Excel.xlsx") is not open in Excel you need to use CreateObject("Excel.Application") and open it.
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Dim xlWorkbook As Object
Set xlWorkbook = xlApp.Workbooks.Open(FileName:="D:\Excel.xlsx") 'will open the workbook
xlApp.Visible = True 'make it false to open Excel invisible in the background
'your code here …
'in the end close workbook and Excel (espaciall if you had it invisible!)
xlWorkbook.Close SaveChanges:=False
xlApp.Quit 'close Excel
Option Explicit
Sub UpdateTables()
Const XLSX = "D:\Excel.xlsx"
Dim xlApp, wb, ws
Dim rngSearch, rngFound
Dim iLastRow As Long, n As Integer
' open spreadsheet
'Set xlApp = New Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(XLSX, 1, 1)
Set ws = wb.Sheets(1)
iLastRow = ws.Cells(ws.Rows.Count, "A").End(-4162).Row 'xlUp
Set rngSearch = ws.Range("A2:A" & iLastRow)
' update tables
Dim doc As Document, tbl As Table, s As String
Set doc = ThisDocument
For Each tbl In doc.Tables
s = tbl.Cell(1, 1).Range.Text
s = Left(s, Len(s) - 2)
Set rngFound = rngSearch.Find(s, LookIn:=-4163, LookAt:=1) ' xlValues, xlWhole
If rngFound Is Nothing Then
MsgBox "'" & s & "' not found in table " & tbl.Title, vbExclamation
Else
tbl.Range.Cells(3).Range.Text = rngFound.Offset(0, 1)
n = n + 1
End If
Next
wb.Close False
xlApp.Quit
MsgBox n & " tables updated", vbInformation
End Sub

VBA - Import Macro - How do i add to the current data when importing?

I have created a macro to import data from another workbook, but i have to set which row to start. I was wondering how i would alter the code to paste the import data to the last empty row (so its adding to the table).
Currently the macro, prompts to click the file you would like to import, then imports the data from certain col from source WB to target WB. But as you can see it as been assigned the row to paste. My question is how do i get it to paste at the last empty row, so it is collecting the data rather then over writing the data.
Would i need to change the "targetSheet.Range("R2", "R4000").Value = sourceSheet.Range("Q2", "Q4000").Value"
Public Sub Extract_Excel_file()
''//--------------------------------------------
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Sheets("Raw Data")
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
sourceSheet.Range("A2", "V400").NumberFormat = "#" ''//Set all cells to
text format.
' sourceSheet.Range("A2", "A4000").NumberFormat = "#" ''//Set all cells
to text format.
targetSheet.Range("B2", "B4000").Value = sourceSheet.Range("A2",
"A4000").Value
targetSheet.Range("C2", "C4000").Value = sourceSheet.Range("B2",
"B4000").Value
targetSheet.Range("D2", "D4000").Value = sourceSheet.Range("C2",
"C4000").Value
targetSheet.Range("E2", "E4000").Value = sourceSheet.Range("D2",
"D4000").Value
targetSheet.Range("F2", "F4000").Value = sourceSheet.Range("E2",
"E4000").Value
targetSheet.Range("G2", "G4000").Value = sourceSheet.Range("F2",
"F4000").Value
targetSheet.Range("H2", "H4000").Value = sourceSheet.Range("G2",
"G4000").Value
targetSheet.Range("I2", "I4000").Value = sourceSheet.Range("H2",
"H4000").Value
targetSheet.Range("J2", "J4000").Value = sourceSheet.Range("I2",
"I4000").Value
targetSheet.Range("K2", "K4000").Value = sourceSheet.Range("J2",
"J4000").Value
targetSheet.Range("L2", "L4000").Value = sourceSheet.Range("K2",
"K4000").Value
targetSheet.Range("M2", "M4000").Value = sourceSheet.Range("L2",
"L4000").Value
targetSheet.Range("N2", "N4000").Value = sourceSheet.Range("M2",
"M4000").Value
targetSheet.Range("O2", "O4000").Value = sourceSheet.Range("N2",
"N4000").Value
targetSheet.Range("P2", "P4000").Value = sourceSheet.Range("O2",
"O4000").Value
targetSheet.Range("L2", "L4000").Value = sourceSheet.Range("P2",
"P4000").Value
targetSheet.Range("Q2", "Q4000").Value = sourceSheet.Range("L2",
"L4000").Value
targetSheet.Range("R2", "R4000").Value = sourceSheet.Range("Q2",
"Q4000").Value
' Close customer workbook
Application.DisplayAlerts = False ''//Don't promt to Save
customerWorkbook.Close
Application.DisplayAlerts = True '' undo Don't promt to Save
End Sub
I just want it to collect the data rather then overriding it each month.

Using PowerPoint VBA to open CSV file in Excel

I am trying to write a PowerPoint VB application which needs to display certain values from a text file in a fixed format.
When I (manually) open that text file as a csv file in Excel, I get the required values in fixed cells and I know how continue from there by VBA.
What I do not know is how to create the Excel spreadsheet using a macro in PowerPoint.
Also, I want to make sure that the parameters for opening the file (using space as delimiter; multiple spaces count as one) are defined in the macro so that I do not have to rely on current local settings.
Thanks in advance for any idea or reference.
use ~.OpenText
it Supports consecutive delimiter
2.Use text file not with .csv but with .txt extension
Excel fails to load a text with other delimiter if it's extension is '.csv'
Following macro reads a text file with delimiters of space character and copies the Excel table to Powerpoint Table on a Slide.
Full code:
Sub ReadCSV()
Dim xlsApp As Excel.Application
Dim xlsWb As Excel.Workbook
Dim xlsSht As Object 'Excel.Worksheet
Dim rng As Object 'Excel.Range
Dim Target As String
On Error GoTo Oops
'Set xlsApp = New Excel.Application
Set xlsApp = CreateObject("Excel.Application")
xlsApp.Visible = True
Target = ActivePresentation.Path & "\test_space.txt"
'Below don't support consecutive delimiters
'Set xlsWb = xlsApp.Workbooks.Open(FileName:=Target, Format:=3)
'File Extension .CSV won't work here. .TXT works.
xlsApp.Workbooks.OpenText FileName:=Target, Origin:=2, StartRow:=1, _
DataType:=1, ConsecutiveDelimiter:=True, Space:=True, Local:=True
Set xlsWb = xlsApp.ActiveWorkbook
Set xlsSht = xlsWb.Worksheets(1)
Dim sld As Slide
Dim shp As Shape
Dim tbl As Table
Dim numRow As Long, numCol As Long
Dim r As Long, c As Long
Set rng = xlsSht.UsedRange
numRow = rng.Rows.Count
numCol = rng.Columns.Count
With ActivePresentation
Set sld = .Slides.Add(.Slides.Count + 1, ppLayoutBlank)
End With
Set shp = sld.Shapes.AddTable(numRow, numCol, 100, 100, 200, 150)
shp.Name = "Table"
Set tbl = shp.Table
'Copy cell values from Excel Table to Powerpoint Table
For r = 1 To numRow
For c = 1 To numCol
tbl.Cell(r, c).Borders(ppBorderBottom).ForeColor.RGB = rgbBlack
With tbl.Cell(r, c).Shape.TextFrame
If r > 1 Then .Parent.Fill.ForeColor.RGB = rgbWhite
.VerticalAnchor = msoAnchorMiddle
.TextRange = rng.Cells(r, c)
.TextRange.ParagraphFormat.Alignment = ppAlignCenter
End With
Next c
Next r
xlsWb.Close False
Oops:
If Err.Number Then MsgBox Err.Description
'If Excel App remains in the system process, Excel App won't respond and run again.
If Not xlsApp Is Nothing Then xlsApp.Quit: Set xlsApp = Nothing
End Sub

Excel VBA import of various excel files to master sheet

I have a master Excel workbook and I want to create a macro to import data from a specified range from 7 Excel files. These files are all the same in structure except for the actual data. With the import macro/button I basically want to get an open files dialogue, select all the files and let the macro add the data in the range to the master one by one. I have taken some Inspiration from another post here, which makes it work for one single file: The to be adjusted code would have to be able to select the 7 files and dynamically add it to the target range one by one.
Sub getData()
Dim slaveBook As Workbook
Dim filter As String
Dim caption As String
Dim slaveFilename As String
Dim slaveWorkbook As Workbook
Dim targetWorkbook As Workbook
Set targetWorkbook = Application.ActiveWorkbook
filter = "Team file (*.xlsm),*.xlsm"
caption = "Please select the team file"
slaveFilename = Application.GetOpenFilename(filter, , caption)
Set slaveWorkbook = Application.Workbooks.Open(slaveFilename)
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets("MASTER")
Dim sourceSheet As Worksheet
Set sourceSheet = slaveWorkbook.Worksheets("Interface")
targetSheet.Range("B5", "J8").Value = sourceSheet.Range("B5", "J8").Value
slaveWorkbook.Close
End Sub
Sub getData()
Dim slaveBook As Workbook
Dim filter As String
Dim caption As String
Dim slaveFilename As String
Dim slaveWorkbook As Workbook
Dim targetWorkbook As Workbook
i = 1
For i = 1 To 7
Set targetWorkbook = Application.ActiveWorkbook
On Error GoTo errorhandler
filter = "Team file (*.xlsm),*.xlsm"
caption = "Please select the team file"
slaveFilename = Application.GetOpenFilename(filter, , caption)
Set slaveWorkbook = Application.Workbooks.Open(slaveFilename)
On Error GoTo 0
On Error GoTo err2
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets("MASTER")
Dim sourceSheet As Worksheet
Set sourceSheet = slaveWorkbook.Worksheets("Interface")
If i = 1 Then targetSheet.Range("B5", "J8").Value = sourceSheet.Range("B5", "J8").Value
If i = 2 Then targetSheet.Range("B9", "J12").Value = sourceSheet.Range("B5", "J8").Value
If i = 3 Then targetSheet.Range("B13", "J16").Value = sourceSheet.Range("B5", "J8").Value
If i = 4 Then targetSheet.Range("B17", "J20").Value = sourceSheet.Range("B5", "J8").Value
If i = 5 Then targetSheet.Range("B21", "J24").Value = sourceSheet.Range("B5", "J8").Value
If i = 6 Then targetSheet.Range("B25", "J28").Value = sourceSheet.Range("B5", "J8").Value
If i = 7 Then targetSheet.Range("B29", "J32").Value = sourceSheet.Range("B5", "J8").Value
slaveWorkbook.Close False 'wont prompt to save changes (will close without saving),
'remove false if you do need to save changes
i = i + 1
Next i
Exit Sub
errorhandler:
MsgBox "You didn't select a valid file!"
Exit Sub
err2:
MsgBox "Error - Most likely reason is that the required sheet is not found in Slave workbook"
Exit Sub
End Sub
Updated - Have changed the code so now it should save all the information to your "MASTER" sheet underneath eachother. Obviously this is a very simple way of doing it, and restricts you to only opening 7 files before the code ends. If you wanted to add more in the future you could simply extend the array and range code or modify the range code to look for the last available row to paste data on (LastRow = Range("J65536").End(xlUp).Row) is a good place to start

A couple of questions about Word macros

I need to grab a list of names from Excel and insert them into a Word document, printing one document per name. The document has some text and a bookmark called "name". The code is below.
First, I want to know if it's possible to detect how long is the list of names in the Excel spreadsheet and grab that, instead of hardcoding the number.
Second, I can't figure out how to delete the text I already put inside the document. When I insert text in a bookmark, it gets appended after the bookmark, so if I keep adding names they all stack together.
Maybe with the code this will be clearer:
Sub insertar_nombre()
Dim Excel As Excel.Application
Dim Planilla As Excel.Workbook
Dim Hoja As Excel.Worksheet
Set Excel = CreateObject("Excel.Application")
Dim Filename As String
Dim fname As Variant
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Title = "Seleccionar Documento de Excel"
.Show
For Each fname In .SelectedItems
Filename = fname
Next
End With
Set Planilla = Excel.Workbooks.Open(Filename)
Set Hoja = Planilla.Worksheets(1)
Dim Nombre As String
For Count = 2 To 10
Nombre = Hoja.Cells(Count, 1).Value
ActiveDocument.Bookmarks("name").Range.Text = Nombre
ActiveDocument.PrintOut
Next
End Sub
Forgive me if this code is obviously wrong or something, I'm just beginning with this.
I need to grab a list of names from Excel and insert them into a Word document, printing one document per name.
Why don't you simply use the mail merge feature?
the following Sub should solve this for you, but you might need to change the way your bookmark is defined.
There is more than one way to insert a Bookmark. This method requires the Bookmark to be inserted by highlighting the text, not simply positioning the cursor at a location in the text.
Sub insertar_nombre()
Dim xlWorkbook As Excel.Workbook
Dim xlWorksheet As Excel.Worksheet
Dim strFilename As String
Dim bkmName As Word.Range
Dim strBookmarkOriginalText As String
Dim lngRowLast As Long
Dim rngRowStart As Excel.Range
Dim rngRowEnd As Excel.Range
Dim rngNames As Excel.Range
Dim rngName As Excel.Range
'Open file dialog and only allow Excel files'
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Title = "Seleccionar Documento de Excel"
'Only let them select Excel files'
.Filters.Clear
.Filters.Add "Excel Documents (*.xls)", "*.xls"
'Check if a file is selected'
If .Show = True Then
'Since AllowMultiSelect is set to False, _
only one file can be selected'
strFilename = .SelectedItems(1)
Else
'No file selected, so exit the Sub'
Exit Sub
End If
End With
'Set the bookmark to a Word range (not a Bookmark object)'
Set bkmName = ActiveDocument.Bookmarks("name").Range
'Save the original text of the bookmark'
strBookmarkOriginalText = bkmName.Text
'Open the Excel file'
Set xlWorkbook = Excel.Workbooks.Open(strFilename)
Set xlWorksheet = xlWorkbook.Worksheets(1)
'Range of the first cell that contains a name'
Set rngRowStart = xlWorksheet.Cells(2, 1)
'Range of the last cell in the column'
lngRowLast = xlWorksheet.Range("A65536").End(xlUp).Row
Set rngRowEnd = xlWorksheet.Cells(lngRowLast, 1)
'Range of all cells from first name cell to last name cell'
Set rngNames = xlWorksheet.Range(rngRowStart, rngRowEnd)
'Loop through the range of names'
For Each rngName In rngNames
'Ignore any blank cells'
If rngName <> vbNullString Then
'Set the text of the bookmark range to the name from Excel'
bkmName.Text = rngName
'The above statement deleted the Bookmark, so create _
a new Bookmark using the range specified in bkmName'
ActiveDocument.Bookmarks.Add Name:="name", Range:=bkmName
'Print the document'
ActiveDocument.PrintOut
End If
Next
'Restore the orignal value of the bookmark'
bkmName.Text = strBookmarkOriginalText
ActiveDocument.Bookmarks.Add Name:="name", Range:=bkmName
'Close the Workbook without saving'
xlWorkbook.Close SaveChanges:=False
End Sub
Hope this helps.

Resources