matlab error when using xlsread in a loop - excel

I'm trying to read multiple csv files, in a loop, and then perform some analysis on all o them.
I'm using MatlabR2015b and Excel 2016.
the problem is that at the second call to xlsread I get the following error:
>>xlsread('R:\Experiments\ResoFreq_vis_BEH\TapFlick_vis_BEH\Data\s01_rr\1_fingerTapping_s01_rr.csv')
Error using xlsread (line 251)
No explanation no message, nothing.
after some debugging I've found it fails at the following command:
Excel.workbooks.Open(filename, 0, readOnly);
in the openExcelWorkbook.m file which is somewhere down the stack of xlsread.
I found very few people with the same problem and their solution was to force the EXCEL32 process to close using the following code:
[~, computer] = system('hostname');
[~, user] = system('whoami');
[~, alltask] = system(['tasklist /S ', computer, ' /U ', user]);
excelPID = regexp(alltask, 'EXCEL.EXE\s*(\d+)\s', 'tokens')
for i = 1 : length(excelPID)
killPID = cell2mat(excelPID{i});
system(['taskkill /f /pid ', killPID]);
end
However, this does not work for me.
after somemore digging I tried to manually look at the csv im trying to open, while debugging, meaning after stopping at the breakpoint at the Excel.workbooks.Open call, I used:
actxserver('Excel.Application')
ans.Workbooks.Open(filename)
which gave me the following error:
Error using Interface.000208DB_0000_0000_C000_000000000046/Open
Which is associated to Workbooks when looking at the excel process through the matlab inspector.
That is all the information I've managed to find related to my problem.
the only thing that works for me at the moment is running xlsread, then manually closing the excel process from the task manager, then running it again, until I have all my data, and then analyze, which is not a possible considering the amount of files I need to load.
I cannot use csvread as my files have mixed types, and every other function i've tried does not read the csvs properly
(I have a field which looks like this "[,...,]" and that field keeps getting interpreted as multiple rows in every function except with xlsread)
and thus I feel like I have no option but to fix xlsread somehow.
I would gladly provide anymore information that is necessary to solve this
thanks.

you should use csvread instead of xlsread, becuase xlsread just read .xls and .xlsx files.

Related

Matlab writematrix in Excel gives error: Name cannot be the same as built-in name

I want to copy an Excel file to a different path through Matlab and then write in it also using Matlab. Somehow I get the error: Name cannot be the same as built-in name.
As I want to write multiple times in the file, I don't want to solve this problem manuelly each time, I want the code to run through without me having to do something constantly.
Is there any way I can solve this problem all at once through code? Does this happen because I copy the Excel file first?
The code looks like this:
path_source_template1 = 'Blabla1\Template1.xlsx';
timestamp = datestr(now);
timestamp = strrep(timestamp, ':', '-');
timestamp = strrep(timestamp, ' ', '-');
path_output = fullfile('Blabla2\',timestamp);
mkdir(fullfile(path_output));
path_output_template1 = strcat(path_output,'\Template1.xlsx');
copyfile(path_source_template1,path_output_template1);
Then I want to write in the Template1.xlsx:
writematrix(test,path_output_template1,'Sheet','Test','Range','A1',UseExcel=true,AutoFitWidth=false);
Then I get this error:
enter image description here
The input to the writematrix file uses the name, value format, so in this line:
writematrix(test,path_output_template1,'Sheet','Test','Range','A1',UseExcel=true,AutoFitWidth=false);
you should have:
..., 'Sheet','Test','Range','A1','UseExcel', true,'AutoFitWidth', false);
Disclaimer: I haven't tested this, but I'm fairly certain this will fix your problem.
The correct call to the writematrix would be:
writematrix(test,path_output_template1, 'Sheet','Test','Range','A1', 'UseExcel', true,'AutoFitWidth',false);
When writing datetime data to a spreadsheet file, you must set both 'PreserveFormat' and the 'UseExcel' Name-Value pair to true to preserve the existing cell formatting. You can check the documentation writematrix.
In order to answer to the error I tested the code locally in Matlab 2019b and works well setting the test variable in this example way: test = magic(5);.
Maybe the error could be in the data that you use in test variable or in that if you run the code iteratively very fast the path_output could exist, One way to improve this could be with a more accurate timestamp.

How to query files (csv, bmp) using NI-488.2 from a GPIB port in VBA (Excel)

Using VBA, I tried to use the NI-488.2 calls directly, instead of using VISA COM. However, when I try to use NI-488.2 commands in VBA, I get the following error message :
''Sub or Function not defined''.
That is, when calling Call SendIFC(BOARD_ID) or Call EnableRemote(BOARD_ID, intAddrList()), Call SendGPIB(osa, ":mmem:stor:grap color,bmp,""test"",int"), = RecieveBinaryGPIB(osa, byteData()), etc...
My first guess would be that I am simply missing the correct library. (Or is there any deeper issue here?). For now, I added the VISA COM 3.0 Type Library and the VISA COM 488.2 Formatted I/O 1.0 to the Excel references.
Here is a sample code from YOKOGAWA (slightly edited) that can be found online and applies to Visual Basics, but that I could not run in VBA. I removed most of the code for clarity purpose. It simply saves a screenshot in internal memory.
Private Sub SaveImage()
Const BOARD_ID = 0 'GP-IB Interface card Address
Const osa = 1 'OSA GP-IB Address
Dim intAddrList(31) As Integer
'----- GP-IB Interface setting
' send IFC
Call SendIFC(BOARD_ID)
' assert th REN GPIB line
intAddrList(0) = NOADDR
Call EnableRemote(BOARD_ID, intAddrList())
' GPIB time out setting
Call ibtmo(BOARD_ID, T30s) 'Time out = 30sec
'----- send command to OSA
Call SendGPIB(osa, "CFORM1") ' Command mode set(AQ637X mode)
Call SendGPIB(osa, ":mmem:stor:grap color,bmp,""test"",int")
'----- Disconnect
Call EnableLocal(BOARD_ID, intAddrList())
End Sub
Now we have the code... you have now edited out the useful bits... I'm going to backtrack a bit and say that even if you get direct calls to work you’re still going to have a problem extracting the files.
I’m going to guess you’re getting "Undefined header" errors if you query the OSA with "SYST:ERR:ALL?" and this is quite possibly because the query command for the data is invalid.
I’ve notice you’re using including the data type your command:
":mmem:data? ""test.bmp"",int"
"test.bmp",int,0 is what you might see if you query the directory, however, it is not needed when extracting the file.
try using:
":mmem:data? ""test.bmp"""
(The number of quotations are to include them in the string)
If not, what is the GPIB error?

Issue with Powershell Excel attempting to cast .csv Values

At this point, I believe it may be a file I/O issue.
While utilizing a Powershell script invoking Excel methods to go through a .csv file from a website, powershell is attempting to cast placeholders for data that is too long for a cell "#######" instead of the date and time contained within the 'cell' (search engines may need 'pound sign' or 'hashtag' to reach this result).
Below is the offending portion of the script.
[DateTime]$S = $sheet.Cells.Item($rowS+$i,$colS).text
[DateTime]$G = $sheet.Cells.Item($rowG+$i,$colG).text
[DateTime]$A = $sheet.Cells.Item($rowA+$i,$colSWScan).text
The data should exist as MM/DD/YYYY HH:MM, but is being read by Powershell/PSExcelModule as #######, which is what is displayed with the Excel GUI when opening the file.
This is only a portion of what the entire script does. Any suggestions on how to resolve the error while maintaining usage of PSExcel-Module would be most helpful.
Stackoverflow seems to have an issue with me posting the verbose error message, and this is my first post. Let me know if that would be helfpul with troubleshooting.
Edit for comment #1:
# Create an instance of Excel.Application and Open Excel file
$objExcel = New-Object -ComObject Excel.Application
# Open the file
$workbook = $objExcel.Workbooks.Open($file)
# Activate the first worksheet
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
After getting my head out of 'Excelland', I realized it may be easier to re-write the script to utilize the .csv organization (the original imported file for the script was a .xlsx), but I am admittedly unfamiliar with .csv scripting. However, the original question still stands while I re-write the code as I may need to switch back to .xlsx imported documents. Thank you for the suggestion J E Carter II.
Answer:
$objExcel.Cells.EntireColumn.AutoFit()
Credit to J E Carter II
When you open an excel file as an object under windows, you're launching excel.
You might be able to add the following commands to your excel object handle to get the data to represent correctly.
$objExcel.Cells.Select
$objExcel.Cells.EntireColumn.AutoFit
Do this before getting values from cells. If that doesn't work, let me know and I can find some csv handling examples.
Those might work better on the $workbook object. I can't remember which is implicit when recording a macro (which is how I got those).
It's also possible you may need to precede those two lines with something like
$workbook.Sheets("sheetname").Select

Extract the ANOVA table to Excel/.csv

I'm wondering if it's possible to extract the table that results when running ANOVA to an Excel or .csv file. I'm running a repeated measures two-way ANOVAs with RMAOV2 (http://uk.mathworks.com/matlabcentral/fileexchange/5578-rmaov2). Here is the code I'm using, which works fine, and it produces a table with the ANOVA results.
dir ='/Users/Documents/folder';
cd(dir)
file = readtable('file.csv');
toAnalyse = table2array(file);
RMAOV2(toAnalyse);
However, when I tried to save the ANOVA results in order to then export them to Excel or in a .csv file, this doesn't work:
ANOVAresults = RMAOV2(toAnalyse);
Error:
Output argument "RMAOV2" (and maybe others) not assigned during call to "RMAOV2".
Any suggestion would be very appreciated.
If you take a look into the source code of the file, you will notice that it never assigns anything to the return variable. Instead it only prints data to the command window.
To resolve this problem you have to edit the source code and assign the data you want to return. Alternatively you can contact the Autor.

SAS - Execute Find and Replace in an Excel File via DDE

I am trying to write a SAS program to do a find and replace in an excel file via DDE. Specifically, I am trying to search the header row for spaces between the strings (i.e., " ") and replace them with no spaces (i.e., "").
For example, if I have a cell that contains "Test Name" I want to do a find and replace to make it "TestName".
This is what I have:
options noxwait noxsync;
/* Open Excel */
x '"C:\Program Files (x86)\Microsoft Office\Office14\excel.exe"';
filename cmds dde 'excel|system';
data _null_;
x=sleep(5);
run;
/* Open File and Manipulate*/
data _null_;
file cmds;
put '[open("C:\filename.xls")]';
put '[select("R1")]';
put '[formula.replace(" ","",1,,false,false)]';
run;
/*Close File*/
data _null_;
file cmds;
put '[FILE-CLOSE("C:\filename.xls")]';
put '[QUIT()]';
run;
The find and replace function is not working. I get the following in my log after it reads that statement:
NOTE: The file CMDS is:
DDE Session,
SESSION=excel|system,RECFM=V,LRECL=256
ERROR: DDE session not ready.
FATAL: Unrecoverable I/O error detected in the execution of the DATA step program.
Aborted during the EXECUTION phase.
NOTE: 2 records were written to the file CMDS.
The minimum record length was 21.
The maximum record length was 70.
NOTE: The SAS System stopped processing this step because of errors.
NOTE: DATA statement used (Total process time):
real time 0.63 seconds
cpu time 0.00 seconds
Any suggestions?
Also, does anyone know what the parameters in the formula.replace statement are? I just know the first and second are what you want to find and what you want to replace it with. I am struggling to find any documentation.
http://www.lexjansen.com/wuss/2007/ApplicationsDevelopment/APP_SmithC_ImportingExcelFiles.pdf
If you enter the path or filename incorrectly, Excel will fail to open your workbook. You will get an error message in the SAS log that looks like the following:
NOTE: The file DDECMD is:
DDE Session,
SESSION=excel|system,RECFM=V,LRECL=256
ERROR: DDE session not ready.
FATAL: Unrecoverable I/O error detected in the execution of the data step program.
Aborted during the EXECUTION phase.
NOTE: 0 records were written to the file DDECMD.
NOTE: The SAS System stopped processing this step because of errors.
My suggestion is to write an excel (VBA) macro to do this, then call that macro; that gives you not only a far superior IDE to write your code in, to get contextual clues and such, but also gives you a lot more control. You can call macros from separate workbooks, so even if this is something you have to do repeatedly (I assume so), you can put this in a 'macro' template workbook that you open up separately from the automated file.

Resources