Search code examples
excelmatlabcomactivexlistobject

Creating an Excel Table with MATLAB


Since writing varying sized data ranges to a sheet seems to remove an Excel Table if the data range is larger than the existing Excel tables range, I want to create a Table in Excel every time I run the code. I'm currently having a fair bit of difficulty creating the tables. The code I have right now to try and create the ListObject:

eSheets = e.ActiveWorkbook.Sheets;
eSheet = eSheets.get('Item', j);
eSheet.Activate;    
eSheet.Range(horzcat('A1:R',mat2str(size(obj,1)+1))).Select;
eSheet.Listobjects.Add;
eSheet.Listobjects.Item(1).TableStyle = 'TableStyleMedium2';
eSheet.ListObjects.Item(1).Name = tablename;

Any commentary or suggestions would be appreciated


Solution

  • Alright, since the post got downvoted (not sure why...) I found my own answer with the help of some VBA forums and MATLAB Newsgroup. Here's what the final code looks like for anyone else that has issues:

        e = actxserver('Excel.Application');
        ewb = e.Workbooks.Open('Path/to/file');
        eSheets = e.ActiveWorkbook.Sheets;
        eSheet = eSheets.get('Item', j);
        eSheet.Activate;
        range = horzcat('A1:R',mat2str(size(obj,1)+1));
        range_todelete = horzcat('A1:R',mat2str(size(obj,1)+300));
        Range1 = eSheet.get('Range',range_todelete);
        Range1.Value=[];
        eSheet.Range(range).Select;        
        name = 'Table_Name';        
        try eSheet.ListObjects(name).Item(1).Delete
        catch
        end
        eSheet.Listobjects.Add;
        eSheet.ListObjects.Item(1).Name = name;
        eSheet.ListObjects.Item(1).TableStyle = 'TableStyleMedium2';
        Range = eSheet.get('Range',range);
        Range.Value = cellarray;