Automatic Word Doc Completion from Excel - excel

I'm after some advice, and certainly open to other suggestions on how to achieve what I'm trying to do here, so feel free to suggest alternatives.
I'm trying to build a quote document where we can automatically populate some fields (they will be product specifications) based on selecting an option in a list box. So far I've created my Drop Down List and populated with 2 options. I've then created 4 'specifications' I want to fill out and created a Content Control for each one.
What I'm trying to do at the moment is populate these content controls from an Excel sheet, where the different List Box items are titles of Sheets, and the specifications are in a column of each sheet.
Sub chillerdatafromexcel()
Dim xlApp As Object
Dim xlbook As Object
Set xlApp = CreateObject("Excel.Application")
Set xlbook = xlApp.Workbooks.Open("C:\Users\chris.garratt\Documents\Chiller Options.xlsx")
'Set xlbook.Sheets = ThisDocument.SelectContentControlsByTitle("Chiller Supplier")
ActiveDocument.SelectContentControlsByTitle("MaxCoolingPwr").Item(1).PlaceholderText = xlbook.Sheets(ActiveDocument.SelectContentControlsByTitle("Chiller Supplier").Item(1).Range).Cells(2, 2)
End Sub
Word example
Excel sheet
Any ideas welcome. I haven't done any text based coding / scripting for a long time, so feel free to dumb it down.
Thanks in advance.
Chris

See:
http://www.msofficeforums.com/word-vba/16330-how-import-list-excel-into-drop-down.html#post46287
Others you might find useful include:
Dependent Dropdown Content Controls
http://www.msofficeforums.com/word-vba/24661-help-cascading-dropdown-list.html#post77762
Hierarchical Dropdown Content Controls
http://www.msofficeforums.com/word-vba/29617-creating-reducing-drop-down-list.html#post94603
Dependent Text Content Controls
http://www.msofficeforums.com/word-vba/16498-multiple-entries-dropdown-lists.html#post46903
http://www.msofficeforums.com/word-vba/16498-multiple-entries-dropdown-lists-5.html#post120392
Content Control & Formfield Conditional Formatting
http://www.msofficeforums.com/word-vba/16505-change-color-according-dropdown-selection.html#post47254
Creating and Tallying Mutually-exclusive Checkbox Content Controls
http://www.msofficeforums.com/word-tables/12335-assigning-values-content-control-checkboxes-calculating-results.html#post33489
http://www.msofficeforums.com/word-tables/33248-content-control-checkbox-calculations.html#post107008
Adding a new row to a table in a document with Content Controls:
http://www.msofficeforums.com/word-vba/27809-code-add-new-row-table.html#post87989
http://www.msofficeforums.com/word-vba/13955-macro-add-row-table-word-form.html#post38461
https://www.msofficeforums.com/word-vba/43603-multiple-dependent-dropdown-lists-table-add-new.html#post145675

Thank you all for your input. macropod, I'm sure those links will come in very helpful as I continue with this project.
I spent some time working on this yesterday before the replies came in, and I did manage to crack it (It's amazing what walking away and coming back with a fresh pair of eyes will do).
In the end, I settled on this:
Sub chillerdatafromexcel()
Dim xlApp As Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Sheets
Dim X As Integer
Dim ChillerOpt As String
Dim Offset As Integer
Set xlApp = CreateObject("Excel.Application")
Set xlbook = xlApp.Workbooks.Open(ActiveDocument.Path & "\Chiller Options.xlsx")
Offset = ThisDocument.SelectContentControlsByTitle("Chiller Supplier").Count
ChillerOpt = ThisDocument.SelectContentControlsByTitle("Chiller Supplier").Item(1).Range
For X = (Offset + 1) To (Offset + 4)
ThisDocument.ContentControls(X).Range = xlbook.Sheets(ChillerOpt).Cells(X, 2)
Next X
xlbook.Close
xlApp.Quit
End Sub
I have a few extra variables in there which will be relevant when I use this function in the context of a larger document. I was going for keeping it as flexible as possible. Avoiding hard coding. I have 4 cells in the spreadsheet I want to pull in, hence the X range.
Thanks for your help.
Chris

Related

I want to read data from two excel sheets to one excel sheet with button using VBA?

enter image description hereI want to read data from two sheets whereas user will enter only date and after clicking button data will be populated in sheet.
Title Date
Enter Week Start Date "7/11/2016" (Button)
Name Project-ID Project Name Project Start Date Project End Date Sum Sum * 20
This is actual format of requirement.
in your line
Set objsheet = bjExcel.ActiveWorkbook.Worksheets("Config_InputAllocation_Weekly")
Set objsheet2 = objExcel.ActiveWorkbook.Worksheets("Config_Project")
you try to set both sheets active, which is not possible. There only be one active sheet. But you don't have to set them active. Use the following technique:
Dim objExcel as Object
Set objExcel = CreateObject("Excel.Application")
Dim myWb as workbook, myws1 as worksheet, myWs2 as worksheet
Set myWb = objExcel.Workbooks.Open("C:\Users\ABC\Documents\NSL\Automation Macro\NSL_DM_Tracker.xlsm")
Set myWs1 = myWb.Worksheets("Config_InputAllocation_Weekly")
Set myWs2 = myWb.Worksheets("Config_Project")
Then you can easily call the data from both sheets whether they are active or not:
Msgbox myWs1.Cells(1,1).value
Msgbox myWs2.Cells(1,1).value
Then the other problem is that you have defined an Sub searchdata() but it is not called within your CommandButton1_Click() Sub.
Moreover use Option Explicit setting, that is, put this line at the very top of your code:
Option Explicit
This will help you to debug your code.
Last but not least, in your Sub searchdata() no Worksheets are defined. Thus it will not know which one (myWs1 or myWs2) to use and when.
Good Luck,
Viktor

SSIS Script Task Delete Row from excel Sheet

I have an SSIS package that creates and populates an excel sheet, it creates the sheet from a template file.
One of the issue's I had was that excel would change the format of the rows. I did a work around of inserting a header row and hiding it.
However I now need to script a VB task in SSIS that opens the excel sheet and deletes that specific row.
I've seen some articles online however have not been able to find any code I can try and replicate and my VB knowledge is very limited and I am really struggling.
SO far i've figured out how to delete the row.
Sub DeleteRow1()
Rows(4).Delete
End Sub
However i need to assign file strings and get the file to open and close as well...
after some discussions with a programmer here i managed to get some script to do exactly what I needed. Posting as an answer for anyone else out there who ever needs to do this in SSIS.
Dim xlApp As Excel.Application
Dim xlSheet As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Workbooks.Open(Dts.Variables("NewFileName").Value.ToString)
xlSheet = xlApp.Workbooks(1).ActiveSheet
xlSheet.Rows(4).Delete()
xlApp.Workbooks(1).Save()
xlApp.Workbooks(1).Close()
xlSheet = Nothing
'
Dts.TaskResult = ScriptResults.Success
Uses a variable in SSIS to get the file name. This works perfectly although you do need to add Microsoft.Office.Interop.Excel Reference.
Sub deleteRow1()
Dim wkbk As Workbook
'You can also use an input box like this
' Dim wkbkname As Variant
' wkbkname = InputBox("Enter Workbook Name here.")
' Use wkbkname instead of wkbk then
Set wkbk = "Filename"
wkbk.Sheets(1).Rows(4).delete
End Sub
I hope that's what you were looking for.

Open excel from Word and perform action

I want to create a marco which enables me to add something in an excel sheet while working in Word. I managed to get something working which opens an excel file from word:
Dim excelApp As Excel.Application
Dim openExcel As Workbook
Dim var1 As Integer
Set excelApp = New Excel.Application
Set openExcel = excelApp.Workbooks.Open("C:\Documents and Settings\aa471714\Desktop\Book1.xls")
excelApp.Visible = True
But now I want to add the code which should happen in excel right after. But when I add the relevant code:
Sheets("Sheet2").Select
Range("A4").Select
This does not seem to work. Am I overlooking something?
Dear regards,
Marc
Keep in mind that in macro created in Word default application is Word Application all the time. Therefore each time you want to make any operation in Excel you need to state it by adding full references to Excel Application (or other Excel object as presented below).
Keep also in mind that you will need to add extended object hierarchy in such situation.
Back to your code- adding this kind of object references should solve the problem:
(incl. some additional re-editions)
'comments referring to Object hierarchy
openExcel.Sheets("Sheet2").Select 'OK because sheet is an object below Workbook
excelApp.Range("A4").Select 'NEW, Range is object below Application or...
openExcel.Sheets("Sheet2").Range("A4").Select 'IMPROVED, Range is object below sheet
'general- Range.Select works only for activesheet!!
Object openExcel keeps reference to Excel application which is represented by excelApp.

Populate Word Combobox with Excel data through VBA

I'm new to VBA, so I'm struggling with this for a couple of days now.
I have a combobox in Word with contacts, I also have an excel file(contacts.xls) with one column (names of the all the contacts). When I open the Word-document the Macro has to fill in the combobox with all the names from the excel file.
Is it possible to send me a working example of this for word 2007? Seems quite simple, but just can't get this to work...
Thanks in advance!
If you intend on reading from an Excel file in Word you are going to have to open it. It will use code like this:
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open("FileName.xlsx")
You will also probably want to go to Tools->References in the VB project and find whatever Excel library is on your machine (and check it of course). There are ways around this if needed, but it is easier.
You then can read the values from the workbook:
oBook.Worksheets(1).cells(1,1)
I'm not totally sure what the syntax to get it into the combo box is. Look up "combobox object members" in the vbe in word. There will be a list property, or something like that.
Sorry, I'm on a linux machine right now, so I can't debug exact code for you.
I have more full code for you now:
Option Explicit
Sub TestDropDownFromExcel()
Dim counter As Long
Dim xlApp As Excel.Application
Dim xlBook As Workbook
Dim oCC As ContentControl
Set oCC = ActiveDocument.ContentControls(1)
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Path\To\MyFile.xlsx")
If xlBook Is Nothing Then
Exit Sub
End If
oCC.DropdownListEntries.Clear
For counter = 1 To 10
oCC.DropdownListEntries.Add Text:=xlBook.Worksheets(1).Cells(counter, 1), Value:=CStr(counter)
Next counter
xlApp.Visible = True
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Be aware that there is very little error checking going on here. Also, rather than the call to .Visible at the end, you can simply call .Close if you do not want the user to see it (for the final project, this is probably preferable. The deferencing (= Nothing) is good practice to have, but VBA cleans up automatically at the end of execution. Obviously I am assuming tyou want the first dropdown (ContentCOntrols(1)) but this may not be true.

VB: Copy a Range to another Excel Application

I'm trying to solve a relatively simple problem but I can't realize it. My aim is to copy a range of cells in a worksheet of the main Excel Application to another range (of the same size) in a worksheet of a second newly created Excel Application. I create the second Application by using
Set secondExApp = CreateObject("Excel.Application")
I'm using this reference for further handling. Until now I've tried two different ways. Both don't work properly.
0.: Preparation / Introduction
Set srcWb = Application.ActiveWorkbook
Set srcSheet = srcWb.Worksheets("example")
Set dstApp = CreateObject("Excel.Application")
Set dstWb = dstApp.Workbooks(1)
Set dstSheet = dstWb.Worksheets(1)
1.: PasteSpecial - delivers an image(!) instead of just the range
srcSheet.Range("A1:B2").Copy
dstSheet.Range("A1:B2").PasteSpecial xlPasteAll
2.: Range.Copy [Destination] - does not work - Is it right that I can only use this method for sheets in the same application?
srcSheet.Range(srcSheet.Cells(..., ...), srcSheet.Cells(..., ...)).Copy _
dstSheet.Range(dstSheet.Cells(..., ...), dstSheet.Cells(..., ...))
Any help is appreciated.
Edit:
I've already played with the "record macro" functionality but I prefer coding it on my own without "selecting" or "activating" cells / sheets / etc.
Edit (solved):
Thank you both GSerg and iDevlop very much, you delivered a good further starting point for me. I did some research as far as the Excel constants as xlClipboardFormatDspText are concerned.
What really helped me was the fact that opening a new Excel instance changes the Paste(Special) menu.
So instead of creating a new instance I now simply add a workbook (which can be hidden) and use this object to add my content. Since it is held in the same instance (also have a look at the task manager) the Paste(Special) menu is completely the same.
Now it is possible to use Range.Copy [destination] even without select!
Result:
'Hides the new workbook
Application.ScreenUpdating = False
Set dstWb = Workbooks.Add
Set dstSheet = dstWb.Worksheets(1)
srcSheet.Range(srcSheet.Cells(..., ...), srcSheet.Cells(..., ...)).Copy
dstSheet.Paste dstSheet.Range(dstSheet.Cells(..., ...), dstSheet.Cells(..., ...))
'Avoids the often seen dashed border around the copied range
Application.CutCopyMode = False
'Setting the initial change back
Application.ScreenUpdating = True
Software: Excel 2007
As determined by poking Excel with a stick, you have to use Worksheet.Paste for inter-excel stuff:
srcSheet.Range("A1:B2").Copy
dstSheet.Paste dstSheet.Range("A1")
Poking Excel with a thicker stick revealed that formulas get preserved when pasting from Clipboard as xlClipboardFormatDspText:
srcSheet.Range("A1:B2").Copy
dstSheet.Range("A1").Select
dstSheet.PasteSpecial xlClipboardFormatDspText, False
However, this does require selecting a cell on dstSheet first, because Worksheet.PasteSpecial uses active cell.

Resources