Deletion of selected rows of excel from Matlab GUI

조회 수: 2 (최근 30일)
raghavendra kandukuri
raghavendra kandukuri 2018년 8월 17일
댓글: raghavendra kandukuri 2018년 8월 21일
HI, I am new to MATLAB and I am trying to delete all rows except 1st and 2nd where I gave headers. But the way, for example if there are 100 rows, this code is deleting 50 rows, and then if I save that file and try to delete again from MATLAB GUI, it will delete 25 out of those 50 and so on. can any one help me out in understanding what am I doing wrong here.
file = 'C:\Users\rk49845\Documents\MR\experimental TCC\exp2.xlsx';
sheet = 'Sheet1';
Excel = actxserver('Excel.Application');
Workbook = Excel.Workbooks.Open(file);
Worksheet = Workbook.Worksheets.Item(sheet);
for row = 3:100;
Worksheet.Rows.Item(row).Delete;
end
Workbook.Save;
Workbook.Close;
  댓글 수: 2
Adam
Adam 2018년 8월 17일
편집: Adam 2018년 8월 17일
Never delete things in a loop from start to end. If you must delete in a loop then do it from end to start, otherwise you are pulling the rug out from under your feet with your deletions.
Better still is to do all deletions at once based on a set of indices but I don't know if that is possible with what you are doing as I don't interact with Excel in Matlab.
raghavendra kandukuri
raghavendra kandukuri 2018년 8월 17일
@ Image Analyst

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2018년 8월 21일
Like Adam said in the comment above, reverse the order:
for row = 100 : -1 : 3
Worksheet.Rows.Item(row).Delete;
end
  댓글 수: 3
Image Analyst
Image Analyst 2018년 8월 21일
You could also delete them all in one shot:
% Select the range
Excel.Range(cellReference).Select;
% Clear the cell contents.
Excel.Selection.Clear;
% Put "cursor" or active cell at A1, the upper left cell.
Excel.Range('A1').Select;
cellReference would be something like 'A3:Z100'.
raghavendra kandukuri
raghavendra kandukuri 2018년 8월 21일
Thank you @ Image Analyst

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by