Excel Interop Range.Replace方法不起作用

时间:2015-07-14 21:15:34

标签: c# excel vba interop excel-dna

我正在尝试编写一个C#方法,它将从Excel电子表格中删除所有字符集的实例。使用Range对象的Replace方法似乎是最有效的方法,而不是迭代每个单元格。以下是我正在使用的内容:

范围扩展方法:

 public static void ReplaceChars(this Range me, String toReplace, String replacement = "") {

        //App is a static reference to the active Excel instance.
        //Alerts must be suppressed for characters that are not present in data.
        App.DisplayAlerts = false; 

        for (Int32 i = 0; i < toReplace.Length; i++) {
            me.Replace(

                //I'm using "Substring(i,1)" rather than "foreach (Char c in toReplace)" 
                //because Excel maps Char values differently than .NET.
                What: toReplace.Substring(i, 1),

                Replacement: replacement,
                LookAt: XlLookAt.xlPart,
                SearchOrder: XlSearchOrder.xlByRows,
                MatchCase: true,
                MatchByte: false, //I'm not 100% what this arg does
                SearchFormat: false, //Or this one
                ReplaceFormat: false); //Or this one
        }

        App.DisplayAlerts = true;
    }

例如,从这样的主程序调用,只留下标点:

  App.ActiveSheet.Cells.ReplaceChars(
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");

有时'U'不会被替换,有时'T',有时是所有数字。我无法预测它。如果我注释掉设置DisplayAlerts并在for循环中放置断点,我将收到有关未替换的字符的警报。

有没有像Range.Replace这样的问题?我只是没有正确分配论据吗?

1 个答案:

答案 0 :(得分:1)

我认为所有必须要做的是相关范围的NumberFormat属性。我在替换之前添加了这个并且它有效:

ws.Cells.NumberFormat = "@" //Set format to text
foreach (Range col in ws.Cells){ 
     //Iterate through columns rather than doing entire range to reduce memory overhead
     col.Value = col.Value //Flatten any lingering dates to text values
}