在excel工作表对象属性中存储字符串或数值

时间:2017-11-20 09:30:41

标签: c# excel vba excel-vba

我的目的是在工作表对象属性中存储字符串/数值,这对用户来说是不可读写的。

我尝试过如下,但获得例外。

Excel.Worksheet ws = Globals.ThisWorkbook.Application.ActiveWorkbook.ActiveSheet;
ws._CodeName = "abc";

是否有可能在工作表对象中存储自定义值

2 个答案:

答案 0 :(得分:1)

虽然您的代码是c#,但您还显示了VBA标记,因此这里有一个VBA例程,用于将一个customproperty添加到工作表中:

Option Explicit
Sub foo()
    Dim WS As Worksheet
    Dim sCPName As String
    Dim sCPValue As String
    Dim I As Long

Set WS = Worksheets("sheet1")
    sCPName = "Request ID"
    sCPValue = 12345

With WS.CustomProperties
    For I = 1 To .Count
        If .Item(I).Name = sCPName Then Exit For
    Next I

    If I > .Count Then
        .Add sCPName, sCPValue
    Else
        .Item(I).Value = sCPValue
    End If

End With

End Sub

答案 1 :(得分:0)

ws._CodeName是一个ReadOnly属性(MSDN Reference)。因此,您只能阅读它,而不能覆盖它。

但是,如果要更改工作表的名称,可能是这种情况:

using System;
using Excel = Microsoft.Office.Interop.Excel;

class Startup
{
    static void Main()
    {
        Excel.Application excelApp = new Excel.Application();
        Excel.Workbook wkbReport = Open(excelApp, @"C:\Testing.xlsx");
        Excel.Worksheet ws = wkbReport.Worksheets[1];
        Console.WriteLine(ws._CodeName);
        ws.Name = "ABC";
        Console.WriteLine("END");
        excelApp.Visible = true;        
    }

    public static Excel.Workbook Open(Excel.Application excelInstance, string fileName, bool readOnly = false, bool editable = true, bool updateLinks = true)
    {
        Excel.Workbook book = excelInstance.Workbooks.Open(
            fileName, updateLinks, readOnly,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
        return book;
    }
}

这就是它的样子:

enter image description here