Search code examples
c#ms-wordmailmergerecord-count

C# - MS Word - MailMerge how to get Last Record when MailMerge.DataSource.LastRecord returns -16


Unable to get Last record using MailMerge.DataSource.LastRecord or MailMerge.DataSource.RecordCount the first variable always returns -16 and the second one returns -1.


Solution



  • Cause:
    .LastRacord and .RecordCount was returning -16 and -1 because I was reading data from the CSV file.

    Solution: The following code will return the last record or record count reading dataset from CSV file or text file.

    public int GetMailMergeLastRecord()
     {
           Document doc = Globals.AddIn.ActiveDocument;      
           // for storing current record
           int currentRec = (int)doc.Mailmerge.DataSource.ActiveRecord;
    
           //getting the last Record
           int lastRecord = 1;
           doc.MailMerge.DataSource.ActiveRecord = (doc.MailMerge.DataSource.ActiveRecord - (int)doc.MailMerge.DataSource.ActiveRecord) + Int32.MaxValue;
           lastRecord =  (int)doc.MailMerge.DataSource.ActiveRecord;
    
           // resetting the current record as above line of codes will change the active record to last record.
           doc.MailMerge.DataSource.ActiveRecord = (doc.MailMerge.DataSource.ActiveRecord - (int)doc.MailMerge.DataSource.ActiveRecord) + currentRec;
           return lastRecord;
    }
    

    Note
    The above code is for word application level AddIn