以编程方式切换 excel 中的功能区选项卡

问题描述 投票:0回答:0

我是桌面自动化的新手,我想自动执行 Microsoft Excel 的一些操作。我有一个 nunit 测试项目,我正在编写一个测试,它基本上导航到功能区栏中的“查看”选项卡并更改页面布局。

我写了下面的代码

// Create an instance of Excel
Application excel = new Application();

// Make Excel visible
excel.Visible = true;
// Check if there are any open workbooks
if (excel.Workbooks.Count == 0)
{
    // Create a new workbook if there are none open
    excel.Workbooks.Add();
}

// Get the command bars object
CommandBars commandBars = excel.CommandBars;

// Activate the View tab in the ribbon
commandBars["Worksheet Menu Bar"].Controls["View"].ActivateTab();

但是它在 CommandBars 上给我错误,找不到类型或名称空间。我在 COM 中添加了对 Excel 对象的引用。

我正在使用 .net6、Windows 11(在虚拟机上)和 office 2021。

c# excel .net-6.0 office-interop office-automation
© www.soinside.com 2019 - 2024. All rights reserved.