简体   繁体   中英

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

无法使用MailMerge.DataSource.LastRecordMailMerge.DataSource.RecordCount获取最后一个记录,第一个变量始终返回-16,第二个变量始终返回-1。



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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM