Using Excel files to create formatted Word files - excel

I need to create a custom software that would convert Excel files to a formatted Word file.
From the Excel file below;
.
To this word file with the given formatting.
Now I have not done any work in this before. But, I have a few ideas in using Python with CSV file formats but I am not sure. What can I do to write a software that could fully automate this process? For example, take the Excel file as an input and generate a formatted Word file.

You could use the csv module that comes with Python. The function csv.reader() will allow you to iterate through the lines of of your csv file. Additionally, pandas, another Python module (which you have to download) is also a good option when it comes to working with data. However, I'm fairly certain that it won't be automatic, and that you'll have to deal with converting that to a Word file.

Another possibility is:
First, rearrange the data into tabular format, e.g., Name in column A, Gender in column B, etc. You could write a simple VBA routine to create a tabular file based on your raw file.
Use Word's mail merge feature to write the paragraphs by filling data fields from the Excel file.
Hope that helps.

You could use Excel formulas such as =Concatentate to gather the completed sentences onto a separate tab, named for example "Summary", in a named range such as "StudentInfo". Then close the spreadsheet.
In Word, use your skills to get the cursor to the correct spot, then try this:
Sub CopyNamedRangeFromExcelWorkbook()
' For this to work, must go to VB Editor and pick --> Tools > References > Miscorsoft Excel 15.0 Obj Lib
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Dim xlWorkbook As Excel.Workbook
Set xlWorkbook = _
xlApp.Workbooks.Open("C:\Users\Desdemona\Desktop\TheSpreadsheet.xlsx")
xlWorkbook.Worksheets("Summary").Range("StudentInfo").Copy
Selection.Paste ' pastes the excel data as a Word table
xlWorkbook.Close
xlApp.Quit
' now apply a format to the word table, or revert it to text, or whatever.
End Sub

Related

Paste/Copy Range of Cells from Excel to a Bookmark in Word using WORD VBA

I am looking at inserting/pasting a range of text data (40 columns) from Excel into bookmarks in Word. Most of the answers are done using Excel VBA, which is so not practical for my use case as I will have the Word document open, add a button that would run this 'import data' macro. I actually already have a button in the doc that inserts images into bookmarks, so that's one more reason I don't want to do it via Excel VBA.
I know this is not great code, but for the lack of definite leads, I'm throwing it here and hope that this gives you an idea of what I'm trying to achieve:
Sub ImportData()
Workbooks.Open ("\Book2.xlsm")
ActiveWindow.WindowState = xlMinimized
ThisWorkbook.Activate
Windows("Book2.xlsm").Activate
Range("A1:AF1").Select
Selection.Copy
Documents("test.docm").Activate
Selection.GoTo What:=wdGoToBookmark, Name:="Overlay_1"
Selection.Paste
End Sub
PS: It would be great if I could sort of 'transpose' the 40 columns into rows as it is pasted in Word.
Here's an update to my code based off #Variatus 's advice:
Sub ImportData()
Dim wb As Workbooks
Dim ws As Worksheets
Dim objSheet As Object
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
wb.Open ("C:\Users\pc\Documents\Book2.xlsm")
Set objSheet = CreateObject("Excel.Application")
ActiveWindow.WindowState = xlMinimized
Set ws = Workbooks("Book2.xlsm").Sheets("Sheet1")
ws.Range("A1").Value.Copy
With objWord.ActiveDocument
.Bookmarks("Bookmark_1").Range.Text = ws.Range("A1").Value
End With
End Sub
I'm getting this error:
Runtime Error '91':
Object variable or With block variable not set.
Notice how I stuck with a single cell reference for now (A1). I'll just update my code as I learn along the way :)
When you click the button in your Word document you want the following sequence to be initiated.
Create an Excel application object. Make sure that a reference to Excel has been set (VBE > Tools > References) so that Excel's VBA objects are available.
Using the Excel application object, open the workbook. Create an object. Place the object in an invisible window.
Definitely forget about activating or selecting anything in either the workbook or your Word document. The latter is active and remains active from beginning to end. The bookmarks are points in your document you can reference and manipulate by name without selecting them. The Excel workbook is invisible. You can access any part of it using the Range object.
The data you want from your workbook are contained in Worksheets. Be sure to create an object for the worksheet you are about to draw data from.
Excel tables don't translate very well into Word tables. If you do want to go that way I suggest that you use VBA to create the table you want in Excel (transpose the data before you import them into Word). However, you may find it easier to first create the tables you want in Word and then just copy values from your Excel source into the word tables. That would involve taking one cell value at a time and placing it into one Word table cell. Transposing would be done by the algorithm you employ.
Close the workbook. Quit the Excel application. Set the Excel application = Nothing. At the end of your macro everything is as it was before except that your document has data in it which it didn't have before.
Each of the above six points will lead you to at least one question which you can ask here after you have googled the subject and written some code. In fact, I strongly urge you to create one Main procedure (the one which responds to your button click) and let that procedure call various subs which carry out the individual tasks and functions to support the subs. The smaller the parts you create the easier it is to write the code, to find questions to ask and get answers to them. If you plan your project well expect to have about 12 procedures in it by the time you are done. Good luck!

Autorun Excel with VBA script, and auto insert a file based on a date mask

So I have an excel file, which is basically a table.
I have another excel file with a VBA script which is used as a converter for that Excel file to search for specific entries and output them in text.
I've been trying to automate it, but I can't come up with a solution.
This is what the original Excel looks like:
This is how the "converter" looks like
It works like: We open it, click the button, windows pops up, we select the file which has always the same path, and the name of the file is always tomorrows date. It then places the "converted" file into path that has been saved before.
This is what the "converted" version looks like:
So as I mentioned before, I'm looking to automate this step, as this is one of the many mundane tasks that is needed to be performed on daily basis.
I was wondering what my options are.
Maybe it is possible to make the input file get selected automatically?
Or maybe there is a way in which I can extract the VBA script from excel and automate it using Powershell, in which I can set the filenames to be tommorows dates.
Any help is greatly appreciated.
We tried contacting the contractor who made the converter scripts, but we can't reach him anymore.
You can make a vbscript (*.vbs) and run it through opening it or Task Scheduling;
In the script below (which you can simply copy/paste into note pad and save as "Converter.vbs"), you need to change the path to "Converter" workbook, change the name of the macro that does the job.
I would apply a change to your macro too; Instead of an input for name and path, use explicit coding that path is hard-coded in it and get the name based on the system's date. This way there's no need for user interaction with the script.
Option Explicit
'On Error Resume Next ''Comment-out for debugging
ExcelMacro
Sub ExcelMacro()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("\path\to\Converter.xlsm", 0, True)
xlApp.Run "Convert" 'This line runs your macro (called Convert)
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub

How to open a csv file from Excel with a particular line highlighted?

I have a large CSV file and I want to programmatically open it in excel with a particular line highlighted (I know the line number). What is the easiest way to this?
I think my options are:
Auto convert the csv file to an xlsx file. How can I do this from a script?
Give Excel some arguments when it opens up. No idea what command line arguments Microsoft products take.
Somehow interact with Excel after it opens up the CSV file and tell it to highlight a particular. Again not sure how.
I prefer Java/Python/Shell or anything that would work across Mac/Windows assuming the system has Excel installed. So, my best bet is probably #1 which brings me back to the question how can I convert a CSV file to a xlsx file.
You could run a basic vbs which avoids the need to have Excel already open, and conversion isn't necessary.
Paste the code below into a text editor NotePad
Change the path to your CSV file to suit (ie "c:\temp\test2.csv")
Save the file as something like MyCSV.vbs say to your Desktop
Click on the final vbs to open the CSV file to Row X (8 in the sample below)
Dim objExcel
Dim WB
Set objExcel = CreateObject("excel.application")
Set WB = objExcel.Workbooks.Open("c:\temp\test2.csv")
With objExcel
.Goto WB.Sheets(1).Rows(8)
.Visible = True
End With
this works simple save it in an empty workbook.
Private Sub Workbook_Open()
Workbooks.Open ("test.csv")
Range("8:8").Select
End Sub
also if you save that in your normal.dot (the default template document when opening excel) it will run on any document it opens. so what you could do is:
save this to your normal.dot
Private Sub Workbook_Open()
Range("8:8").Select
End Sub
then change the default application for opening .csv files to excel. then whenever you double-click on .csv file it will be opened with excel and excel will run the Workbook_Open() sub and viola!

Save custom data in Excel workbook

Is it possible to save large amount of data (about 1-2 mb) in Excel workbook?
Ideally, this data should be tied with a worksheet in the workbook.
CustomProperties are unlikely to support large data.
My data can be presented in following forms: binary, xml, string.
Thanks...
Yes, you could store string and XML in Excel cells. For binary you'd be better off not saving it inside Excel, but if you had to then OLE (object linking and embedding) could
be an option. You could do so by saving the binary as a file outside of Excel and then inserting it as a OLE object:
Dim mySht As Worksheet
Dim oleFileName as String
oleFile = "MyXmlDoc.xml"
Set mySht = ActiveWorkbook.ActiveSheet
mySht.Shapes.AddOLEObject Filename:=Environ$("Appdata") & _
"\MyFolder\" & oleFile, _
Link:=False, DisplayAsIcon:=True
It worked fine for us for certain types of common filetype. But we never did it for raw binary data. Usually we put a Word Document or PDF in the spreadsheet. You also run the risk of possibly corrupting the workbook or losing the binary data. In our case the OLE object would be clicked on by a user that had Wordperfect instead of Word or they ran Linux / Mac and the embedded document wouldn't open.
It does make the Excel File get rather large with every embedded object you add. It's an old technology with its quirks.
You could add a VBA module to the workbook for your data and encode your data in normal ASCII strings (for example, using Base64 encoding). Resulting code would look like this:
Dim x(1000) As String
Sub InitData()
x(0) = "abcdefghijk...."
x(1) = "123456789......"
'...'
End Sub
You can also store these strings in a sheet instead of a VBA module, line-by-line, if you prefer this.
To accomplish the encoding / decoding, look here:
How do I base64 encode a string efficiently using Excel VBA?
Base64 Encode String in VBScript
http://www.source-code.biz/snippets/vbasic/12.htm
If your information comes in files, you can read the file in binary mode and put it in a cell. Then in the end or in the beginning you would save your filename so you could easily reconstruct the file.
Here is some code for you to begin with:
Sub readBin()
Dim iFreeFile As Integer, bTemporary As Byte
iFreeFile = FreeFile
Open "\temp.bin" For Binary Access Read As iFreeFile
Do While Not EOF(intFileNum)
Get iFreeFile, , bTemporary //read byte from file
Cells(1, 1) = bTemporary //save in cell
Loop
Close iFreeFile
End Sub

Exporting Access Query to Excel

I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.
Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.
Any suggestions or ideas a very welcome.
The short story, is you can't. You might be able to do some scripting on the Excel side to format the resulting file. If you want something pretty, you probably want to create a report.
You could, instead mount the excel sheet as a table, and then on a separated sheet in the excel file, reference the first sheet, and format the second sheet for viewing.
if you use DoCmd.TransferSpreadsheet and create an original and then edit it so that the formatting is correct, you can then run DoCmd.TransferSpreadsheet again and it will update the file with the values but keep the formatting.
However, if a human then changes the file by adding new tabs, or adding calculations, etc, then the DoCmd.TransferSpreadsheet will no longer work and will fail with an ugly error message. So what we do in our enviroment is DoCmd.TransferSpreadsheet to an original file with formatting, and follow that up in the VBA by copying the file to the users desktop, and then opening that copy so the user doesn't mess up the original source excel file.
This approach is a minimum code, clean, and easy to maintain solution. But it does require a extra "source" or original file to be hanging around. Works in Access 2007.
You also would like the results to end up on a new tab. Unfortunately, I think it will take some excel automation to do that. The VBA inside Acccess can call a function inside the VBA in Excel. That VBA could then copy the tabs as needed.
My idea would be a hybrid of Excel automation from Access and creating a template in Excel as well that would have a data table linked to your query.
To start create your data table in Excel. You can start three rows down and two columns to the right if you want or wherever. Go to your data tab and click access, find your db, choose your query you want to link to, choose table as the radio button but click properties next instead of ok, uncheck the enable background refresh, this part is critical ... under the definition tab in the connection string you will see a part that says Mode=Share Deny Write change that to Mode=Read, this will make sure that the query refreshes without errors from an MS Access VBA while the db is open and will keep your users from writing back to the db in case your query is a writeable query. Once you set that up you can adjust the table formatting however you choose from the table design tab and it will keep that formatting.
For the purposes of this we are going to assume you started the table in cell B4 ,and your named the worksheet CurrentDay, for purpose of the following VBA example be sure to replace that reference with your actual placement.
Next go back to Access and write your VBA first ensure that in your VBA window you have the reference to Microsoft Excel 12.0 Object Library is selected by going to Tools > References and selecting it from the alphabetical listing.
Create your sub as follows:
Sub query1_click()
Dim xl as Excel.Application
Dim wbk as Excel.Workbook
Dim wks as Excel.Worksheet
Dim RC as Integer
Dim CC as Integer
Set xl = New Excel.Application
Set wbk = xl.wbk.Open "X:\Filelocation\FileName.xlsx" 'name and path you saved the file you previously created
xl.Visible = True
'The above is not necessary but you may want to see your process work the first few times and it will be easier than going to task manager to end Excel if something fails.
RC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("B:B")) + 3 'This will count the rows of data in your table including your header so you can copy the data to another tab dynamically as the size of your table expands and shrinks we add 3 to it because we started at row 4 and we need the location of the last row of the record set.
CC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("4:4")) + 1 'This counts the header row and adds one space because we will use this as a location holder for our copy / paste function
Set wks = xl.wbk.Worksheets.Add
wks.Name = format(date(),"MM_dd_yy") 'this will name the tab with today's date... you can eliminate this step if you just want the sheets to be the generic Sheet1, Sheet2, etc.
With xl.wbk
.Worksheets("CurrentDay").Range(Cells(4,2),Cells(RC,CC)).Copy
.wks.PasteSpecial xlPasteValues 'This pastes the values so that the table links do not paste otherwise every tab would just refresh everyday.
.wks.PasteSpecial xlPasteFormats 'This gets your formatting.
.RefreshAll 'This will refresh your table
Wend
With xl
.Save
.Close False
.Quit
Wend
Set xl = Nothing
Set wbk = Nothing
Set wks = Nothing
End Sub
That should get you to have your data to not start on A1 of your sheets, save your old data each time, and automate the steps from access.

Resources