Excel Interop Range.Replace 方法无效
Excel Interop Range.Replace method not working
我正在尝试编写一个 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 问题吗?我只是没有正确分配参数吗?
我认为这一切都与相关范围的 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
}
我正在尝试编写一个 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 问题吗?我只是没有正确分配参数吗?
我认为这一切都与相关范围的 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
}