簡體   English   中英

如何知道合並單元格中的可編輯單元格地址

[英]How to know editable cell address in merged cells

在此處輸入圖片說明

在這里,有四個單元格(A1,B1,C1,D1)已合並,我想獲得可編輯的單元格地址(A1)。 根據 Excel A1 Cell 可以編輯,其他不可編輯。 我可以使用下面的代碼將合並的單元格計數為 4。 我也可以知道單元格是否已合並。 但無法獲取合並單元格中可編輯單元格(A1)的地址。

                Microsoft.Office.Interop.Excel.Application appl = null;
                appl = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook wbk;
                wbk = appl.Workbooks.Open("C:\\Users\\test\\Desktop\\test.xlsx");
                Worksheet sheet = wbk.Worksheets.get_Item(1);

                Range range = sheet.Cells[1, 2]; //B1 Cell

                var a = range.Cells.MergeArea.Count;  // can be able to get merged count cells

                string b = range.Address;
                **int ab = range.Cells.Areas.Count;**
                Range ac = range.Cells.Areas.get_Item(1);

                for (int i = 1; i <= 4; i++)
                {
                    **if (sheet.Cells[1, i].Mergecells)**   //merged cell
                    { 
                       MessageBox.Show("Merged");
                    }
                    else //Unmerged cell
                    {
                       MessageBox.Show("UnMerged Cells");   
                    }
                }
                wbk.Save();
                wbk.Close(false);
                appl.Quit();

Range 的MergeArea屬性又是一個 Range。 如果您有一個單元格,只需使用如下所示的內容來獲取合並區域的第一個(=左上角)單元格(在 C# 中未經測試,因為我沒有它,但在 VBA 中有效,也應適用於 C#) :

Range range = sheet.Cells[1, 2];
Range firstCell = range.MergeArea.Cells[1, 1];

即使未合並單元格, MergeArea也有效,始終設置MergeArea ,因此未合並的單元格rangefirstCell將指向同一個單元格。

如果我正確理解了您的真正需求,請嘗試下一種方法。 它基於合並區域將值保留在其第一個單元格中的事實:

'your existing code...
                if (sheet.Cells[1, i].Mergecells)   //merged cell
                    { 
                       MessageBox.Show(sheet.Cells[1, i].MergeArea.cells[1, 1].Value);
                    }
                    else //Unmerged cell
                    {
                       MessageBox.Show(sheet.Cells[1, i].Value);   
                    }
'your existing code...

這是解決方案

string mergedCellsAddress = mergedRange.Address;
string[] firstMergedCell = mergedCellsAddress.Split(':');
string firstCell = firstMergedCell.GetValue(0).ToString().Replace("$", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM