【VSTO开发-Excel】遍历选中范围的cell,首尾有空格则去掉以及文本如果有空格则都去掉

  • 遍历选中范围的单元格,去除单元格中文本首尾的空格:
using Microsoft.Office.Interop.Excel;

namespace YourVSTOAddInNamespace
{
    public partial class ThisAddIn
    {
        private void TrimLeadingTrailingSpacesInSelectedRange()
        {
            Worksheet activeSheet = (Worksheet)Application.ActiveSheet;
            Range selectedRange = Application.Selection;

            foreach (Range cell in selectedRange.Cells)
            {
                if (cell.Value != null && cell.Value is string)
                {
                    cell.Value = cell.Value.ToString().Trim();
                }
            }
        }
    }
}
  • 遍历选中范围的单元格,去除单元格中文本中的所有空格:
using Microsoft.Office.Interop.Excel;

namespace YourVSTOAddInNamespace
{
    public partial class ThisAddIn
    {
        private void RemoveAllSpacesInSelectedRange()
        {
            Worksheet activeSheet = (Worksheet)Application.ActiveSheet;
            Range selectedRange = Application.Selection;

            foreach (Range cell in selectedRange.Cells)
            {
                if (cell.Value != null && cell.Value is string)
                {
                    cell.Value = cell.Value.ToString().Replace(" ", "");
                }
            }
        }
    }
}

你可能感兴趣的:(excel,c#,wps)