You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#获取Excel指定名称工作表ID,实现Worksheets.get_Item()调用

How to Get a Worksheet's ID by Name and Use It with Worksheets.get_Item()

Absolutely, this is totally achievable! Let me walk you through exactly how to make this work for you—this is a common task when working with Excel’s object model, so you’re definitely on the right track.

First, a quick heads-up: the Worksheets.get_Item() method actually accepts both worksheet names and their index/ID values directly. So you don’t strictly need to convert a name to an ID if your only goal is to select the target sheet—but if you specifically need the ID for other workflows, here’s how to get it and use it:

Step 1: Get the Worksheet’s ID (Index) by Name

In Excel, a worksheet’s "ID" typically refers to its index number (the position of the sheet in the workbook, starting at 1 for the leftmost sheet). You can retrieve this easily using the sheet’s name:

Example in VBA

' Define your target sheet name
Dim targetSheetName As String
targetSheetName = "Sheet_Beta" ' Replace with your desired sheet name

' Get the sheet's index (ID)
Dim sheetID As Integer
sheetID = ThisWorkbook.Worksheets(targetSheetName).Index

Example in C# (using Office Interop)

using Microsoft.Office.Interop.Excel;

// Assume you already have a reference to your workbook
string targetSheetName = "Sheet_Delta";
int sheetID = workbook.Worksheets[targetSheetName].Index;

Step 2: Use the ID with Worksheets.get_Item()

Once you have the index ID, you can pass it to get_Item() to select or interact with the sheet:

VBA Example

' Select the sheet using its ID
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets.get_Item(sheetID)
targetSheet.Select ' Activates the sheet

C# Example

Worksheet targetSheet = workbook.Worksheets.get_Item(sheetID);
targetSheet.Select(); // Activates the sheet

Bonus: Skip the ID Conversion Entirely

Since get_Item() works with names directly, you can bypass converting to an ID if you don’t need the ID for anything else. This is often simpler and more readable:

VBA Shortcut

Set targetSheet = ThisWorkbook.Worksheets.get_Item("Sheet_Alpha")
' Or even more concise:
Set targetSheet = ThisWorkbook.Worksheets("Sheet_Alpha")

C# Shortcut

Worksheet targetSheet = workbook.Worksheets.get_Item("Sheet 2");
// Or:
Worksheet targetSheet = workbook.Worksheets["Sheet 2"];

So to answer your core question: Yes, your request is fully feasible—you can either convert the sheet name to its index ID first, or just use the name directly with Worksheets.get_Item() to select your target worksheet.

内容的提问来源于stack exchange,提问作者AerWyn81

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:37:08