33043

Fill in word form field with more than 255 characters

Question:

I am trying to programmaticly fill in a microsoft word form. I am successfully able to do so if the string is under 255 chars with the following code below, however it says the string is too long if i try and use a string over 255 chars... How do I get past this limitation? If I open the word doc in word I can type in more than 255 chars without a problem. Does anyone know how to input more characters via c# code?

object fileName = strFileName; object readOnly = false; object isVisible = true; object missing = System.Reflection.Missing.Value; //open doc _oDoc = _oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); _oDoc.Activate(); //write string _oDoc.FormFields[oBookMark].Result = value; //save and close oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); _oWordApplic.Application.Quit(ref missing, ref missing, ref missing);

Answer1:

Here's my C# translation of the workaround Microsoft offers at <a href="http://support.microsoft.com/kb/163192" rel="nofollow">http://support.microsoft.com/kb/163192</a>

using Word = Microsoft.Office.Interop.Word; public void CreatePackage(string filePath, string longText) { Word.Application wordApp = new Word.Application(); Word.Document doc = wordApp.Documents.Open("MyOriginalDoc.docx"); try { //If the document is protected Select() will throw an exception if (doc.ProtectionType != Word.WdProtectionType.wdNoProtection) { doc.Unprotect(); } foreach (Microsoft.Office.Interop.Word.FormField f in doc.FormFields) { //My situation prohibits me from adding bookmarks to the document, so instead I'm //using sentinel values that I search the doc for. if (f.Result.Equals("MySentinalValue")) { //You need some easily removed dummy characters in the field for this to work. f.Result = "****"; //If you don't follow these next three steps you'll end up replacing the formfield //rather than inserting text into it f.Range.Select(); wordApp.Selection.Collapse(); wordApp.Selection.MoveRight(Word.WdUnits.wdCharacter, 1); //Insert the text wordApp.Selection.TypeText(longText); //Now remove the dummy characters. If you don't re-select the range, Find won't catch the //the first one. f.Range.Select(); Word.Find find = wordApp.Selection.Find; object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; find.ClearFormatting(); find.Text = "*"; find.Replacement.ClearFormatting(); find.Replacement.Text = ""; 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); } //Restore the doc protections. Note that if NoReset != true all data entered in fields will be lost doc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, true); doc.SaveAs(filePath); } catch (System.Exception ex) { Console.WriteLine(ex.Message); } finally { doc.Close(); wordApp.Quit(); } }

Answer2:

No, this limitation could not be bypassed using the Result property of the bookmark field.<br /> I have bypassed the problem replacing the bookmark with my text

// Loop on the bookmarks collection foreach(Bookmark bk in workDoc.Bookmarks) { currentData = GetCurrentDataForBookmark(bk.Name); // Insert the value or cut away the bookmark if data is zero lenght bk.Select(); if(currentData.Length == 0) _myWordApp.Selection.Cut(); else _myWordApp.Selection.Text = currentData; }

This approach requires that you make a copy of the orignal document and use it like a template because at the end of the update the bookmarks collection is wiped out.

Answer3:

i overcome this problem by slicing the long text into 248-char size and then looping through find and replace function .. here is my code

int repeat; if (Value.Count() > 254) repeat = ((Value.Count() / 255)); //string spiltedText; else repeat = 0; if (repeat > 0) { for (int i = 0; i <= repeat; i++) { try { spiltedText = Value.Substring(i * 248, 248); spiltedText += "<الوصف>"; } catch { spiltedText = Value.Substring(i * 248, Value.Count() - (i * 248) - 1); } range.Find.Execute(findtext, findmatchcase, findmatchwholeword, findmatchwildcards, findmatchsoundslike, findmatchallwordforms, findforward, findwrap, findformat, spiltedText, findreplace, missing, missing, missing, missing); } } else range.Find.Execute(findtext, findmatchcase, findmatchwholeword, findmatchwildcards, findmatchsoundslike, findmatchallwordforms, findforward, findwrap, findformat, spiltedText, findreplace, missing, missing, missing, missing); }

Notice the spiltedText size is 248 from the function Substring(),then concatenating it with <الوصف> -which will make it 255-char size- the word i`ll search for and replace with the next spiltedText

when the left long text is less than 248 it will throw and exception leading you to the catch statement , which will Substring the last less-248-chars into spiltedText without adding <الوصف> the word that will search for..

the code is tested :)

Recommend

  • How to embed file to word docx?
  • How can I move the cursor to a postion where I want in office word by vb?
  • Replace image inside Word bookmark from Excel
  • Single property not getting bound on HttpPost
  • Is there a way to query if array field contains a certain value in Doctrine2?
  • Arabic data transfer between multiple tables in different MySQL databases returning ???????? as new
  • how do I store a youtube embed link in a database
  • Why does mysqli fetch() return empty results from longtext column?
  • Error while uploading file to Amazon S3 bucket
  • Read BuiltInDocumentProperties/CustomDocumentProperties alway null with Word 2010?
  • How get paragraph FontName with Docx dll?
  • Word Add-in - How to read custom document property
  • Word 2007 VBA: ActiveDocument.CustomXMLParts
  • powershell Get-Counter -ComputerName parameter on Windows 7
  • Xamarin MonoAndroid Azure mobile service InsertAsync
  • Suqueries in select clause with JPA
  • Exception creating JSON with LINQ
  • Can I read an iPhone beacon with Windows.Devices.Bluetooth.Advertisement.BluetoothLEManufacturerData
  • TFS 2015 - Waiting for an agent to be requested
  • Uncaught TypeError: $(…).select2 is not a function
  • URLConnection doesn't work since API 10 and higher?
  • 550 Access denied - Invalid HELO name
  • Remove changes from one element when event occurs on another element?
  • Problems installing Yesod for Haskell
  • Button click event not firing in jQuery
  • Chart.js Multiple dataset
  • How do I exclude a dependency in provided scope when running in Maven test scope?
  • How do I get HTML corresponding to current DOM tree?
  • Converting a WriteableBitmap image ToArray in UWP
  • JQuery Internet Explorer and ajaxstop
  • JSON response opens as a file, but I can't access it with JavaScript
  • Lost migrations and Azure database is now out of sync
  • Why value captured by reference in lambda is broken? [duplicate]
  • Launch Runnable Jar from Web Start
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • javascript inside java/jsp code
  • Change an a tag attribute in JavaScript based on screen width
  • Android Studio and gradle
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • How can i traverse a binary tree from right to left in java?