none
Problem when copying/pasting string from an Excel cell to a Word Bookmark RRS feed

  • Question

  • Initially, I was setting the variable Lev1Summ = to the value of the cell C18, and then setting the value of the MS Word bookmark = to the value of the variable. 

    If ThisWorkbook.Sheets(2).Range("H18").Value <> "" Then
            Lev1Summ = ThisWorkbook.Sheets(2).Range("H18").Value
            myDoc.Bookmarks("Lvl1OxidesBkmk").Range.Text = Lev1Summ
        End If


    The problem was that the string contains a bunch of oxides whose numbers are subscripted.  The subscript was not copying over, so I next tried setting the bookmark = to the value of the cell itself.  Same problem.

    Finally, I tried a copy/paste, as shown below, and it worked.  Unfortunately, now when I paste the value of the cell into the bookmark, it inserts a paragraph mark after it.  How do I correct this issue?  What am I missing?  (I checked, and that paragraph mark does NOT exist in the Word template until I paste the contents of Cell H18 into the bookmark.)

    If ThisWorkbook.Sheets(2).Range("H18").Value <> "" Then
            ThisWorkbook.Sheets(2).Range("H18").Copy
            myDoc.Bookmarks("Lvl1OxidesBkmk").Range.PasteAndFormat wdFormatOriginalFormatting

    End If

    Friday, February 22, 2019 7:14 PM

All replies

  • Hi DanNatCorning,

    I'm not sure if I can understand your question.
    I'd like to confirm:
    (1) Data Type of a variable "Lev1Summ" (String? Variant?...)
    (2) how about using .Value, instead of .Text
        myDoc.Bookmarks("Lvl1OxidesBkmk").Range.Text = Lev1Summ
    Regards,

    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    Thursday, February 28, 2019 11:00 PM
  • Hi,

    Simply use the component(https://www.nuget.org/packages/FreeSpire.Office/) and do it with the following code.

     Workbook workbook = new Workbook();
     workbook.LoadFromFile(@"sample1.xlsx");
     Worksheet sheet = workbook.Worksheets[2];
    
     CellRange range = sheet.Range["H18"];
     string text = string.Empty;
     if (!string.IsNullOrEmpty(range.Text))
     {
         text = range.RichText.RtfText;
     }
    
     Document document = new Document();
     document.LoadFromFile(@"sample2.docx");
     BookmarksNavigator bn = new BookmarksNavigator(document);
     bn.MoveToBookmark("Lvl1OxidesBkmk", true, true);
     Paragraph paragraph = new Paragraph(document);
    
     paragraph.AppendRTF(text);
     bn.InsertParagraph(paragraph);
    
     document.Sections[0].Paragraphs.Remove(paragraph);
     document.SaveToFile("output.docx", Spire.Doc.FileFormat.Docx);



    • Edited by adam_hugo Tuesday, March 5, 2019 9:17 AM
    Tuesday, March 5, 2019 9:15 AM