加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将公式添加到Excel工作表将导致HRESULT:0x800A03EC

发布时间:2020-12-15 23:37:13 所属栏目:百科 来源:网络整理
导读:我在网上搜索了一个合适的解决方案但找不到任何有用的东西…… 在Excel工作表中,我需要从数据库表中分配一些值,然后在每个值旁边添加一个公式(取决于同一工作簿中的另一个Excel工作表).添加数据非常有效,但添加公式会导致错误. 我正在获取数据并将其添加到工
我在网上搜索了一个合适的解决方案但找不到任何有用的东西……

在Excel工作表中,我需要从数据库表中分配一些值,然后在每个值旁边添加一个公式(取决于同一工作簿中的另一个Excel工作表).添加数据非常有效,但添加公式会导致错误.

我正在获取数据并将其添加到工作表中,如下所示:

using (SqlConnection conn = new SqlConnection("MyConnectionString"))
using (SqlCommand comm = new SqlCommand("SELECT DISTINCT [MyField] FROM [MyTable]",conn)
{
    conn.Open();
    using (SqlDataReader reader = comm.ExecuteReader())
    {
        myStringList.Add("MyField");
        if (reader.HasRows)
            while (reader.Read())
                myStringList.Add(reader.GetString(reader.GetOrdinal("MyField")));
    }
}

workbook.Worksheets.Add(After: workbook.Worksheets[workbook.Sheets.Count]);

for (int counter = 1; counter <= myStringList.Count(); counter++)
    ((Excel.Worksheet)workbook.ActiveSheet).Cells[counter,1] = myStringList[counter-1];

到现在为止还挺好.现在我遇到了我的问题.我需要为A列中每个使用过的单元格添加一个公式到单元格B2,B3,….难点是我想用for循环来完成,因为公式取决于A列.

for (int counter = 2; counter <= myStringList.Count(); counter++)
    ((Excel.Worksheet)workbook.ActiveSheet).Range["B" + counter].Formula
        = $"=VLOOKUP(A{counter};MyOtherWorksheet!$B$2:$B${numberOfRows};1;FALSE)";

numberOfRows是MyOtherWorksheet中B列的行数(它在调试器中返回正确的数字,所以这不是问题).

但是,当我分配这样的公式时,我得到以下异常,没有任何有用的消息:

HRESULT: 0x800A03EC

我尝试将.Range [“B”计数器]更改为.Cells [counter,2]甚至尝试使用.FormulaR1C1而不是.Formula但我得到了相同的异常.

我错过了什么?

解决方法

我发现了这个问题.我不得不将.Formula改为.FormulaLocal.

MSDN description for .FormulaLocal

Returns or sets the formula for the object,using A1-style references in the language of the user. Read/write Variant.

MSDN description for .Formula

Returns or sets a Variant value that represents the object’s formula in A1-style notation and in the macro language.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读