How to insert new column to existing excel sheet?

My aim is to insert new column/Cells (for specific range e.g B2:B8 ) with out interrupting other cells or data.More specific i want to insert New cells without disturbing remaining pattern and data. If it is possible using actxserver kindly share your experience with me thanks.

 Accepted Answer

Not tested:
excel = actxsever('Excel.Application');
wb = excel.Workbooks.Open('somefile.xlsx');
ws = wb.Worksheets.Item('sheetname');
ws.Range('B2:B8').Insert;
%other code
wb.Save;
excel.Quit;
delete(excel);
edited for numerous errors!

9 Comments

ws = wb.Worksheet('sheetname'); this line gives the following error :please fix it for me...Thanks
Index exceeds matrix dimensions.
Sorry, should have read:
ws = wb.Worksheets('sheetname'); %the s at the end of Worksheets is important
same Error message:
index exceeds matrix dimensions
Oh, yes, I forgot that matlab is a bit awkward with some overloaded functions. Either of these should work:
ws = wb.Worksheets.Item('sheetname'); %E.g. 'Sheet1'
ws = wb.Worksheets.Item(sheetnumber); %e.g. 1
Thanks:The above line worked but
ws.Range('B2:B8').Shift; now show error:
No appropriate method, property, or field Shift for class Interface.Microsoft_Excel_12.0_Object_Library.Range.
Not sure why I wrote shift. As per the link I wrote, it should have been:
ws.Range('B2:B8').Insert;
I did say it was untested!
Thanks alot. IT worked.. But how i will enter data to this new cells?
The easiest way is probably to use the matlab supplied xlsread and xlswrite functions:
[n t data] = xlsread(...)
data(:,3:end+1) = data(:,2:end);
data(2:8,2) = %your new stuff...
xlswrite(..., data);
But if you want to do it all yourself (and there are reasons you might), then the code in xlswrite probably tells you how to add stuff in a way you want.
To write values to a range:
ws.Range('B2:B8').Value = [1 2 3 4 5 6 7]'; %array must be same shape as range

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!