Save custom data in Excel workbook - excel

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

Related

Adding a "." to the name of a Workbook without changing its format in VBA

Just began coding in VBA so this might be a basic question. My script saves a workbook with a concatenated name. However, within the concatenation I must add a ".", VBA thinks I am referring to the format of the newly saved file when I am still editing its name. The result is a saved file that can't be run because no program identifies the format.
Any thoughts on this?
Sub Save_New_File ()
Dim wb1 As Workbook
Dim CarModel As String
Dim Month As Integer
CarModel = "Corolla"
Month = 10
wb1.SaveAs Filename:=CarModel+"."+Month
End Sub
Adding the format extension at the end of the string fixed the issue. I did not add it the first time thinking VBA would save the file using the same format of the Workbook I was moving the specific sheet out of (what I referred to as "file"). I will add the extension at the end as well as the FileFormat parameter to be sure.
Thank you,

Using Excel files to create formatted Word files

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

Microsoft Access Runtime 2013 - import from Excel

I developed an Access database solution that is using Excel automation to open xls and xlsx files so I can import specific cells that I need.
Now I had to deploy my software to an user that does not have Office nor Excel installed and is using Runtime do run my program and I can not use automation any more.
Is there any way I can open an Excel file without Excel and import lets say cell B7 and cell E4 ? I dont need to import it in the table directly but to operate with results from xls in the memory (as I did with Excel object) and save it later.
Thanks in advance.
With some (quite severe) limitations, it is possible to use Jet (i.e., the Access database engine, an ageing version of which is a standard Windows component) to read XLS files at least. For the limitations see here:
http://support.microsoft.com/kb/257819/en-gb
As for an example...
Function ReadCell(XLSFileName As String, SheetName As String, CellName As String)
Dim DB As DAO.Database, RS As DAO.Recordset
Set DB = DBEngine.OpenDatabase(XLSFileName, False, True, "Excel 8.0;HDR=No;")
Set RS = DB.OpenRecordset("SELECT * FROM [" + SheetName + "$" + CellName + ":" + CellName "]")
ReadCell = RS(0)
RS.Close
DB.Close
End Function
Sub Foo
MsgBox ReadCell("C:\Users\ExeBat\Documents\Test.xls", "Summary Details", "C5")
End Sub
My guess is not without a 3rd party library of some sort. Potentially you could read the file as text if it was stored as office open XML, my guess is that MS encrypts/obfuscates your standard xls/xlsx file by default so you cannot though. If Excel isn't available on your user machines in all cases you might need to look into having the source data in another format (text, csv, etc), I know that is probably not an ideal answer though.

Changing connection string in Excel messes up column data types

This is related to my previous question. I'm trying, in Excel, to update external data connections to text files (used by several pivot tables) to point to the correct data sources so data can be refreshed when the Excel workbook and text files are copied to a different directory/computer. (It should act like the paths to the text files are relative.)
The data sources are tab delimited text files with the headers in the first columns. I have code that can change the path in the ODBC connection string, but when I try to refresh the data Excel imports it all as text, not keeping some of the columns numeric as they originally were.
Public Sub Test()
Dim wb As Excel.Workbook
Dim pc As PivotCache
Dim path As String
Set wb = ActiveWorkbook
path = wb.path
For Each pc In wb.PivotCaches
'Debug.Print pc.Connection
pc.Connection = "ODBC;DBQ=" & path & ";DefaultDir=" & path & ";Driver={Microsoft Text Driver (*.txt; *.csv)};DriverId=27;FIL=text;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Threads=3;UserCommitSync=Yes"
Next
End Sub
I tried changing MaxScanRows to zero, which I read somewhere would have Excel scan all the rows to guess the data type, but that didn't seem to help.
The original connection info is:
Connection String:
DefaultDir=C:/directoryPath;Driver={Microsoft Text Driver (*.txt; *.csv)};
DriverId=27;FIL=text;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;
SafeTransactions=0;Threads=3;UserCommitSync=Yes;
Command Text:
SELECT *
FROM tableName.txt tableName
When I created the connection with the PivotTable wizard (External Data -> MS text driver) I set up all the import/parsing information (tab delimited, column headers in first row, guess data types, etc).
Is there any way to (1) tell Excel to look through the rows and figure out the data types, (2) manually code in the data types for each column, (3) keep the same data types that were originally used, or (4) after the data is refreshed go through the pivot tables in the macro and convert all the numbers to numeric values instead of text? Obviously (1) or (3) seem like they would be easiest and make the most sense, but I'm willing to try other options.
Given your requirements, it would seem that using a schema.ini would be the best bet.
For example:
[mycsv.csv]
Format=Delimited(|)
NumberDigits=2
CurrencyThousandSymbol=,
CurrencyDecimalSymbol=.
CurrencyDigits=2
DateTimeFormat="yyyy-mm-dd"
Col1=ADate Date
Col2=AText Text
Schema.ini File (Text File Driver)

How do you save an Excel HTML text file to an Excel xls binary file?

This is one of the questions that is asked alot, but the text to binary mechanism is left out in the question and the answer. If you export to html from excel it is an Excel html file. Is there a tool that can be used for automation purposes to then take this html excel file and convert it back into an Excel .xls binary file? (Note: Binary is a requirement.) Also is it possible in both 2003 and 2007 or greater?
The reason I ask it this way is because there is a little known secret: You can save an Excel html file as .xls. Which is not what I am looking for. I'm trying to find the elusive "Holy Grail" answer to convert an excel html (which is bound to an excel html schema) to binary .xls file.
The business pursose is becase an excel binary file will be much smaller and load much faster than its HTML counterpart especially when file sizes get into the 10Megabyte range and greater.
In VBA:
Sub Tester()
Const FOLDER_PATH As String = "C:\path\to\files\"
Dim wb As Workbook
Set wb = Workbooks.Open(FOLDER_PATH & "NoName.html")
wb.SaveAs Filename:=FOLDER_PATH & "NoName.xls", FileFormat:=xlExcel8
End Sub

Resources