vba 通过 C# 设置 Excel 命名范围?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2416727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:24:32  来源:igfitidea点击:

Set Excel Named Ranges via C#?

c#excelvbavstonamed-ranges

提问by Chapax

I'm trying to replicate this Access VBA code using C#, but am unable to do so. Wondering if anyone else has tried this before and can help.

我正在尝试使用 C# 复制此 Access VBA 代码,但我无法这样做。想知道是否有其他人以前尝试过这个并且可以提供帮助。

oWB.Worksheets("Signoff").Range("rgSignOffRecTemplate").Value = g_TemplatePath & "Signoff_Rec.XLT"

oWB.Worksheets("Signoff").Range("rgSignOffRecTemplate").Value = g_TemplatePath & "Signoff_Rec.XLT"

rgSignOffRecTemplateis a "Defined Name" in the Excel template that I'm trying to write to.

rgSignOffRecTemplate是我尝试写入的 Excel 模板中的“定义名称”。

Many thanks for your help.

非常感谢您的帮助。

回答by AMissico

    private void ThisWorkbook_Startup(object sender, System.EventArgs e)
    {
        Excel.Name oName;
        Excel.Range oRange;

        //'using name
        oName = ExcelWorkbook1.Globals.ThisWorkbook.Names.Item("rgSignOffRecTemplate", missing, missing);
        oName.RefersToRange.Value2 = "here";

        //'using range
        oName = this.Names.Item("rgSignOffRecTemplate", missing, missing);
        oRange = oName.RefersToRange;
        oRange.Value2 = "here i am";

        //'direct access
        this.Names.Item("rgSignOffRecTemplate", missing, missing).RefersToRange.Value2 = "here i am again";

        DisplayWorkbookNames();

    }

    private void DisplayWorkbookNames() {
        for (int i = 1; i <= this.Names.Count - 1; i++) {
            Globals.Sheet1.Range["A" + i.ToString(), missing].Value2 = this.Names.Item(i, missing, missing);
        }
    }