На всякий случай, если кто-то ищет что-то похожее в C #:
private static void ReplaceText(Find find, string findText, string replaceText) {
find.ClearFormatting();
find.Text = findText;
find.Replacement.ClearFormatting();
find.Replacement.Text = replaceText;
object replaceAll = WdReplace.wdReplaceAll;
find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}
private static void ReplaceTextInRange(Range range, Dictionary<string, string> replacements) {
var find = range.Find;
foreach (var replacement in replacements) {
int maxLen = 255;
if (replacement.Value.Length > maxLen) {
//For longer text, we need to break it up. We use a special delimiter at the end of each chunk to mark the position for the next replacement operation.
const string specialDelim = "{={=}=}";
ReplaceText(find, replacement.Key, specialDelim);
var chunkSize = maxLen - specialDelim.Length;
SplitIntoChunks(replacement.Value, chunkSize, (chunk, i, isLast) =>
ReplaceText(find, specialDelim, chunk + (isLast ? "" : specialDelim))
);
} else {
ReplaceText(find, replacement.Key, replacement.Value);
}
}
}
private static void SplitIntoChunks(string value, int size, Action<string, int, bool> fn) {
var cnt = (int)Math.Ceiling((decimal)value.Length / size);
if (cnt <= 1) {
fn(value, 0, true);
}
for (int i = 0; i < cnt; i++) {
string chunk = value.Substring(i * size, Math.Min(size, value.Length - i * size));
fn(chunk, i, i == cnt - 1);
}
}