Error using the User Defined function of Excel in Matlab [duplicate] - matlab

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Excel Addin Error #NAME?
I think it is a follow-up query to my earlier reported issue concerning User defined function in Excel.
I am able to use the function in Excel when used Manually, but when I write to an excel file using Matlab using xlswrite, it gives an error #NAME?
I am attaching the screenshots of the both when entered manually and when using the function through Matlab.
Thanks
EDIT :
Thanks a lot. I have stored the VBA function as an Excel addin here :
C:\Users\Administrator\AppData\Roaming\Microsoft\Addins
Here is what I saw about Excel Add-ins not loaded when used in Automation :
http://www.excelforum.com/excel-programming/472145-calling-excel-macro-from-vb-6-app-problem.html
I am attaching the small snippet of the code from chi_squared() here :
Function Chi_Squared(act, exp, Optional df)
This is how I write to an excel file in Matlab :
Formula_chisqr={[ '=chi_squared(' 'O2:O22' ',' 'M2:22' ')']};
[status, message] = xlswrite1(ExcelFilename,Formula_chisqr,sheetname, Location_Agg);
I also tried giving the complete path as suggested. But it did not work.
Thanks

You have to specify the workbook where the UDF defined. Even if your function is it your PERSONAL.XLSB file. You don't have to do it only if UDF is defined in the same file where you use it.
For example,
='myFunctions.xlsb'!chi_squired(O2:O21,P2:P21)
If myFunctions.xlsb is not opened you may need to specify full path to the file.
If you want to be able to call UDF in any file without specifying the file name, you need to save the file as Add-in, and then enable it in Options - Add-ins - Manage Add-ins.
Another idea: When you use XLSWRITE provide file name with extension XLSX, like test.xlsx, not just test. By default MATLAB saves files with XLS extention in older format. It looks like when you open such file in newer version of Excel (2007/2010) the compatibility mode does not allow macros or UDFs to run.

When you open the Excel as a COM server, the UDF's and Add-ins are not loaded by default. So, you need to first load the add-ins if you would like to use the add-in your Excel file.
Here is the small code snippet in Matlab which loads the add-ins before opening the Excel file.
Excel = actxserver ('Excel.Application');
Excel.Workbooks.Open('C:\YourAddInFolder\AddInNameWithExtension');
Excel.Workbooks.Item('AddInNameWithExtension').RunAutoMacros(1);
File='C:\YourFileFolder\FileName';
if ~exist(File,'file')
ExcelWorkbook = Excel.Workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);
end
Excel.Workbooks.Open(File);
Source : Mathworks

Related

How to programmatically open and modify ODT file from Calc Macro

I am writing a Macro programm in a LibreOffice Calc spreadsheet. This macro should do the following (amongst other things):
open an existing ODT text document as a template
search and replace some strings with new values
save a copy of this as a new file
generate and open a PDF version
Is this possible somehow using LibreOffice Basic only? I have found nothing in the Libreoffice docs and examples and only this slightly related answer here on SO: How to programatically modify Open/Libre Office odt document?
Thanks!
open an existing ODT text document as a template
The method to open a document is loadComponentFromURL, for example https://help.libreoffice.org/6.4/en-US/text/sbasic/shared/stardesktop.html. There is nothing especially difficult about opening a document in Writer from a Calc macro, as LibreOffice components are well integrated. Remember to use the object returned from opening the document instead of ThisComponent.
search and replace some strings with new values
Andrew's Macro Document section 7.14. Search And Replace shows some ways to do this.
save a copy of this as a new file
The command is storeAsURL which is like "save as", not to be confused with storeToURL which would modify the existing file. See https://wiki.openoffice.org/wiki/Saving_a_document.
generate and open a PDF version
Generating a PDF is like any other save. The only difference is that the export filter writer_pdf_Export must be specified. An example is at https://ask.libreoffice.org/en/question/178818/how-i-export-pdf-using-macro/.
As for opening the PDF, what application do you want to open it? LibreOffice Draw can open a PDF although it's not a normal PDF viewer. Shell can call the viewer of your choice.

Perl parse an .xlsm file without using excel

I have an input .xlsm file from which I have to parse some values.
Currently I am using Win32::OLE which from certain reasons I need to stop using.
Is there a way to parse that file without using EXCEL processes?My searches on google lead me to Spreadsheet::ParseXLSX module and Excel::Writer::XLSX(with some problemes), but I don't know whether they require Excel or not.
Thank you!

Options to compile a Matlab application with Excel GUI

I am developing a Matlab application for myself and for others using a GUI on Excel (for ease of use but also because some data processing need to be done in Excel).
To simplify, here are all the parts making up my application:
Part 1: Excel GUI with run settings
Part 2: Matlab program creating data results and images
Part 3: Excel GUI with Matlab data & image results and aditionnal Excel data processing
Currently, when others need to use it, they give me the run settings (Part 1), I run the Matlab program for them (Part 2) and give them the data, images and my last Excel GUI (Part3).
I am trying to improve the situation by combining the parts above. I see 2 options:
Option 1: Running Matlab from Excel (Spreadsheet Link EX Toolbox) therefore having Part1 & Part2 together
=> would be more for me (I have Matlab, and I can see more info from running my Matlab code)
Option 2: Packaging it all: Part 1+2+3 in an executable (MATLAB Compiler Toolbox)
=> would be for my end users (no Matlab needed)
Now my questions:
Can I (Should I? Should I not?) do both options? or am I over complicating everything? and should not use Excel Link toolbox at all?
Do I need Matlab Builder EX to achieve Option 2? (therefore creating an Add-in) or could I also achieve this with the toolboxes: Excel Link + Compiler? (No Add-in, but VBA code?)
Cheers!
If you choose to use the MATLAB Compiler, the following is what I imagine the steps would be
create a GUI in MATLAB. It will present an interface that allows the user to input some settings. It also has a "RUN" button that will run your MATLAB program with those parameters.
at the end of your alorithm, use COM automation to open Excel and programmatically fill tables with the results of the previous step. You could add snapshots of any generated MATLAB figures and plots to the excel file (see here for an example) or simply save as separate image files. You could even add VBA macros to the sheet.
Deploy the above as a standalone application. It will not depend on MATLAB (only the freely available MCR runtime has to be installed by the user).
The user runs your application, and use it to generate the Excel file. Now the user can optionally open this file, and manually perform any final data manipulation.
If you want additional integration, you could use the "Spreadsheet Link EX" toolbox.
HTH
There is a great answer which kind of answer my question.
MATLAB Compiler vs MATLAB Coder
Basically:
For R2014b and ealier version: It is possible to produce Excel add-ins with the "MATLAB Builder EX for Excel" toolbox
From R2015a (recent release): The toolbox "MATLAB Compiler" can now produce Excel add-ins
This simplify things a lot!
Nico (answering his own question :-) )

Opening an existing workbook from Matlab using ActiveX

I need to open an existing excel workbook from within Matlab using ActiveX. xlsread is unfeasible because too slow. After getting help from this forum (thanks!) I know that to create a new excel workbook from within matlab and fill it with output you do this:
%# Create and NAME the output file name
wbk=1;fName = fullfile(pwd, 'ALLSDtemp2');
%# create Excel COM Server
Excel = actxserver('Excel.Application');
Excel.Visible = true;
%# delete existing file
if exist(fName, 'file'), delete(fName); end
%# create new XLS file
wb = Excel.Workbooks.Add();
wsheet=1;
(...calculations...)
% Write output to excel file
Mat=[calculation_output];
% Select work book
wb.Sheets.Item(wsheet).Activate();
% Get Worksheets object
ws = wb.Sheets;
%# insert matrix in sheet
Excel.Range(cellRange).Select();
Excel.Selection.Value = num2cell(Mat);
But I can't figure out how to do this with an excel workbook that already exists. And my efforts to do so caused a "serious error" in my computer the other day. So I could really use some guidance.
Thanks
XLSREAD is actually accessing the file through ActiveX, the same way you want to go. I don't see any reason to write you own (and hopefully clear of bugs) procedure.
If XLSREAD is too slow, you can use PROFILER to find performance bottlenecks in the function.
You can actually see what XLSREAD is doing if you type edit xlsread. The m-file with the function will be opened in the MATLAB editor. You can learn the code and actually run it line by line with great MATLAB debugging tools.
I'm not sure from your question whether you wish to just modify an existing Excel file, or to modify an Excel file that is currently open in Excel.
If it's the first, then you can open it like this:
xl = actxserver('Excel.Application');
xl.Visible = true;
wb = xl.Workbooks.Open('path_to_my_excel_file');
and then continue with whatever modifications you want, as you're already doing.
If you want to access an Excel file that is currently open in Excel, use actxGetRunningServer instead of actxserver. You will connect to the running copy of Excel and be able to find whatever workbooks are open.
By the way, you don't need to select a range to change its value. You can just use ws.Range(cellRange).Value = myValue. Might save you a few lines of code here and there.

How to most effectively automate repetitive Excel task?

I want to automate Excel using Perl to do the following task(s):
For a list of Excel .xls files, do the following:
Open the file
Set Format to CSV
Save the file under the original filename and directory, but replace the extension "xls" with "csv"
Close the file
End
I found how to open files, even how to save them. I did not find how to change the fileformat/save as a different format. There shall be no user dialogs popping up, it should be fully automated. The Excel file list I can generate myself, a parameterized "find" or maybe "dir" should suffice.
If you are using Excel automation a great help is Excel itself. Use the VBA environment (Alt+F11) to get help for the Excel objects you want to use.
The objectbrowser (F2) is very valuable.
Workbook.SaveAs([Filename], [FileFormat], [Password], [WriteResPassword], [ReadOnlyRecommended], [CreateBackup], [AccessMode As XlSaveAsAccessMode = xlNoChange], [ConflictResolution], [AddToMru], [TextCodepage], [TextVisualLayout], [Local])
Searching for CSV in the object browser will show Excel constants with their values, since you probably cannot use these Excel constants in Perl.
See Spreadsheet::ParseExcel and xls2csv, they will help you.