简体   繁体   中英

C# Excel Cut/Paste cells conditionally

How do I check my two columns (column I and column H) to see if in column I, if any cells are non-empty, and column H the cells are empty then cut and paste the non empty cell from column I to the empty cell in column H.

For a more clear example :

在此处输入图片说明

My idea so far was as so:

xl.Range ColH = sourceSheet.UsedRange;
        xl.Range ColI = sourceSheet.UsedRange;
        string occupiedCellsH;
        string emptyCellsI;
        occupiedCellsH = ColH.ToString();
        emptyCellsI = ColI.ToString();

        if (string.IsNullOrEmpty(emptyCellsI) && occupiedCellsH != null)
        {
            ColH.Cells.Copy(ColI);;
        }

This will do the trick:

        const int hCol = 8;
        const int iCol = 9;

        //start at 1 as there are column headings
        for (int i = 1; i < sourceSheet.UsedRange.Rows.Count; i++)
        {
            if ((sourceSheet.cells[i, hCol].value??"").ToString()!="" && 
                (sourceSheet.cells[i, iCol].value??"").ToString()=="")
            {
                sourceSheet.cells[i, iCol].value = sourceSheet.cells[i, hCol].value;
                sourceSheet.cells[i, hCol].value = "";
            }
        } 

To do the reverse as per your comment (assuming you still need this):

        const int hCol = 8;
        const int iCol = 9;

        //start at 1 as there are column headings
        for (int i = 1; i < sourceSheet.UsedRange.Rows.Count; i++)
        {
            if ((sourceSheet.cells[i, iCol].value??"").ToString()!="" && 
                (sourceSheet.cells[i, hCol].value??"").ToString()=="")
            {
                sourceSheet.cells[i, hCol].value = sourceSheet.cells[i, iCol].value;
                sourceSheet.cells[i, iCol].value = "";
            }
        } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM