微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

试图弄清楚为什么for语句与if语句一起使用,但是在我将其切换为for循环时抛出异常

如何解决试图弄清楚为什么for语句与if语句一起使用,但是在我将其切换为for循环时抛出异常

抱歉,由于我几年前在VB中使用C#大约只有一个月,而历史有限。我正在尝试创建一种邮件合并类循环,以使其工作更轻松。我知道了日期。我有一个Numupdown控件,它设置int myInt一个formCount int从0开始。 当我将if(formCount==0),切换到

时,代码运行良好
for(formCount=0;formCount<myInt;formCount++)

它现在抛出一个

“ System.NullReferenceException:'对象引用未设置为 对象的实例。'“

我知道可能有另一种方法可以做,就是每次只将一个连续的日期添加一个月中。我将日期存储在数组myDate[31]中。

我正在使用numUpDwn(min 1 max 31)获取myInt,因此我们可以选择一个月中的几天,或者如果需要替换页面则仅打印几天,因此我们可以从1开始打印到31页。

使用if语句,它将创建从模板(.dotx)doc(var)的第一页,将doc的内容复制到doc2并添加页面以接收下一个内容粘贴。

我确信这是一个愚蠢的问题,有人也会有一个简单的答案。该循环应该打开模板,添加日期,然后复制到doc2。关闭原件,然后重新启动,直到达到选择的页数/日期。感谢您的帮助,这是我需要完成的最后一部分,我很困惑。哦,我用!=是因为它跳过了合并字段,但是只有1个字段不等于任何有效值。

private void BtnPrint_Click(object sender,EventArgs e)
       {
           var app = new Microsoft.Office.Interop.Word.Application();
           var doc = new Microsoft.Office.Interop.Word.Document();
           var doc2 = new Microsoft.Office.Interop.Word.Document();
           //app.Visible = true;
           doc = null;
           doc2.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
           doc2.PageSetup.TopMargin = app.InchesToPoints(0.6f);
           doc2.PageSetup.BottomMargin = app.InchesToPoints(0.17f);
           doc2.PageSetup.LeftMargin = app.InchesToPoints(0.5f);
           doc2.PageSetup.RightMargin = app.InchesToPoints(0.5f);
           String fileSave;
           fileSave = ("OTSU" + "_" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
           
           
           int formCount;
           //formCount = 0;
           var filepath = System.Windows.Forms.Application.StartupPath + outfile;
           doc = app.Documents.Add(filepath);
           
           doc2.Activate();
           //OBJECT OF MISSING "NULL VALUE"
           Object oMissing = System.Reflection.Missing.Value;
           for (formCount = 0; formCount<myInt;formCount++)
           {
               doc.Activate();

               foreach (Microsoft.Office.Interop.Word.Field field in doc.Fields)
               {

                   Range rngFieldCode = field.Code;
                   String fieldText = rngFieldCode.Text;
                   // ONLY GETTING THE MAILMERGE FIELDS
                   if (fieldText.StartsWith(" MERGEFIELD"))
                   {
                       Int32 endMerge = fieldText.IndexOf("\\");
                       Int32 fieldNameLength = fieldText.Length - endMerge;
                       String fieldName = fieldText.Substring(11);
                       // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dotx FILE
                       fieldName = fieldName.Trim();
                       if (fieldName != "M_2nd__3rd")
                       {
                           field.Select();
                           app.Selection.TypeText(myDate[formCount].ToShortDateString());
                       }
                       formCount++;
                       Microsoft.Office.Interop.Word.Range dRange = doc.Content;
                       dRange.copy();
                       
                       doc2.Range(doc2.Content.End - 1,doc2.Content.End - 1).PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteOptions.wdKeepSourceFormatting);
                       doc2.Range(doc2.Content.End - 1,doc2.Content.End - 1).InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
                       Clipboard.Clear();
                       doc.Close(WdSaveOptions.wdDoNotSaveChanges);
                   }

               }
           }
           doc2.SaveAs2("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
           app.Documents.Open("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
           doc.Close(WdSaveOptions.wdDoNotSaveChanges);
           doc2.Close(WdSaveOptions.wdDoNotSaveChanges);


解决方法

我还没有运行您的代码,但是据我所知,在您有多个MERGEFIELD字段的情况下,即使没有formcount循环,该代码也可能会失败,因为您关闭了doc因为您已经处理了这样的字段,但是foreach循环正在处理doc.Fields中的每个字段。

即使该foreach循环正常终止,在formCount循环的下一次迭代中,您仍在使用doc.Activate(),但是doc已关闭,因此将失败。

因此,我建议主要要做的是考虑在该点上需要打开哪些文档才能使流程正常工作。

一些观察(不一定与您的主要问题有关)

  • myInt设置在哪里?
  • doc中的每个MERGEFIELD中都有一个formCount ++循环在循环内使用formCount ++吗?
  • 过滤MAILMERGE字段而不是匹配文本时,最好不要测试field.Type(),至少是如果最终用户可以设置这些字段
  • 当您在Word中处理集合并且要添加或删除集合的成员时,有时您必须考虑使用从集合的最后一个成员开始并向后开始的循环。不确定在这种情况下是否需要执行此操作,但是由于您在输入字段时可能会“删除”。请选择Typetext,请记住这一点
  • 当您主要试图勾勒出循环的逻辑时,这似乎很复杂,但是我发现开始使用try ... catch ... finally最终在开发过程中而不是稍后进行阻塞很有帮助。
,

我确实找到了解决方案。由于只有一个MERGFIELD,因此无需尝试打开文档,插入日期,复制到新doc2,关闭文档,重复操作,我发现我可以打开,插入日期,复制到新doc2,撤消对文档的编辑并重复操作。至少现在它可以正常工作,在规划计划的大项目时,我可以回到书本上学习更多。我敢肯定我会在这里有更多问题。如果没有@ snakly-snarky询问他所做的问题,我将不会想到这一点,因此我必须给他们功劳。我确实必须把doc.Undo();放进去。在循环的顶部,并且仅适用于一个字段。但这是一个开始。

     private void BtnPrint_Click(object sender,EventArgs e)
    {
        var app = new Microsoft.Office.Interop.Word.Application();
        String fileSave;
        fileSave = ("OTSU" + "_" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
        int formCount;
        formCount = 0;
        var filepath = System.Windows.Forms.Application.StartupPath + outfile;
        var doc = new Microsoft.Office.Interop.Word.Document();
        doc = app.Documents.Add(filepath);
        app.Visible = true;
        doc.Activate();
        var doc2 = new Microsoft.Office.Interop.Word.Document();
        doc2.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
        doc2.PageSetup.TopMargin = app.InchesToPoints(0.6f);
        doc2.PageSetup.BottomMargin = app.InchesToPoints(0.17f);
        doc2.PageSetup.LeftMargin = app.InchesToPoints(0.5f);
        doc2.PageSetup.RightMargin = app.InchesToPoints(0.5f);

        doc2.Activate();
        //OBJECT OF MISSING "NULL VALUE"
        Object oMissing = System.Reflection.Missing.Value;
        for (formCount = 0; formCount < myInt; formCount++)
        {
            doc.Undo();
            foreach (Microsoft.Office.Interop.Word.Field field in doc.Fields)
            {
                Range rngFieldCode = field.Code;
                String fieldText = rngFieldCode.Text;
                // ONLY GETTING THE MAILMERGE FIELDS
                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    Int32 endMerge = fieldText.IndexOf("\\");
                    Int32 fieldNameLength = fieldText.Length - endMerge;
                    String fieldName = fieldText.Substring(11);
                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dotx FILE
                    fieldName = fieldName.Trim();
                    if (fieldName != "M_2nd__3rd")
                    {
                        field.Select();
                        app.Selection.TypeText(myDate[formCount].ToShortDateString());
                    }
                    Microsoft.Office.Interop.Word.Range dRange = doc.Content;
                    dRange.Copy();
                    doc2.Range(doc2.Content.End - 1,doc2.Content.End - 1).PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteOptions.wdKeepSourceFormatting);
                    doc2.Range(doc2.Content.End - 1,doc2.Content.End - 1).InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
                    Clipboard.Clear();
                }
            }
        }
        doc2.SaveAs2("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
        doc.Close(WdSaveOptions.wdDoNotSaveChanges);
        doc2.Close(WdSaveOptions.wdDoNotSaveChanges);
        app.Documents.Open("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
    }
}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。