0

I have a loop that reads tables from several excel files in a folder. However I get the following error:

  Unable to open file 'C:\MATLAB\Data\fish\~$volume022017.xlsx' as a workbook. Check that
the file exists, read access is available, and the file is a valid
spreadsheet file.

I suspect that this is a temporary file (which I am unable to see in explorer). The list of files is created using 'dir':

filesData = [dir([folder,'\*.xlsx']);dir([folder,'\*.xls'])];
filenames = {filesData.name}';

'filenames' also does not list this file.

I then use

tmpTable=readtable( [folder, filenames{i}],'sheet',Tabs{term},'ReadRowNames',true);

which gives the error.

Mary
  • 788
  • 6
  • 19
  • 43
  • Very strange. Have you try to debug it? Check the value of `i` while the error occurs, then check the file in this cell-number inside `filenames` – Adiel Apr 03 '17 at 10:44
  • I checked the file name and I suspect a previous loop has opened and closed it. I built in a pause in the second loop which gives excel time to remove it naturally and this solves the issue but is a bit of a crude solution. – Mary Apr 03 '17 at 10:54
  • If you call `dir` at the beginning, the names in it should not be affected by opening or closing files. Matlab will try to open only the files that you read into `filesData` – Adiel Apr 03 '17 at 11:07
  • Agreed. However the structure of the code requires it to be called again because it checks for new additions to the folder. That is why dir is called twice. – Mary Apr 03 '17 at 11:50
  • Ok, so just adding `pause` before the second `dir` is not so crude IMO – Adiel Apr 03 '17 at 11:58
  • Thanks. Yes it works for now. Just curious whether there is a way to stop dir doing this in general. Could also be difficult to guess the length of the pause necessary. – Mary Apr 03 '17 at 12:44
  • 1
    You can easily after the `dir`, remove all the file names that contain `~$` for example. – Adiel Apr 03 '17 at 12:50

1 Answers1

0

you can filter filenames to the ones that do not contain the $:

    filesData = [dir([folder,'\*.xlsx']);dir([folder,'\*.xls'])];
    filenames = {filesData.name}';

    filenames2 = filenames(~contains(filenames,'$'))
ReZzT
  • 33
  • 5