C# 使用 Excel 搜索功能

C# Using Excel Search Function

我正在将 VBA 过程移植到 C# 项目。我即将完成所有工作,但还剩下 2 个错误。这是语法:

public static void ExcelPort()
{
object What = "*";
object After = xlWorkSheet.get_Range("A1", "IV65536");
object LookIn = Excel.XlFindLookIn.xlValues;
object LookAt = Excel.XlLookAt.xlPart;
object SearchOrder = Excel.XlSearchOrder.xlByRows;
Excel.XlSearchDirection SearchDirection = Excel.XlSearchDirection.xlNext;
object MatchCase = System.Reflection.Missing.Value;
object MatchByte = System.Reflection.Missing.Value;
object SearchFormat = System.Reflection.Missing.Value;

currentsheet = (Excel._Worksheet)(xlWorkBook.ActiveSheet);
activeworkbook = (Excel.Workbook)xlApp.ActiveWorkbook;
int lastrow = 0;

foreach (Excel.Worksheet sheet in activeworkbook.Worksheets)
{
    if (usedrows = (double)xlApp.WorksheetFunction.CountA(sheet.Cells) != 0)
    {
        lastrow = sheet.Cells.Find(What,After,LookIn,LookAt,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat);
    }
    else
    {
        lastrow = 1;
    }
}
}

错误列表和行

//This  line throws an error
(double)xlApp.WorksheetFunction.CountA(sheet.Cells) != 0

//Error:
Cannot implicitly convert type 'bool' to 'double'

//This line throws an error        sheet.Cells.Find(What,After,LookIn,LookAt,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat)

//Error:
Cannot implicitly convert type 'Microsoft.Office.Interop.Excel.Range' to 'int'

对于您的第一个错误,这只是不正确的 C# 语法,与 Excel:

无关
if (usedrows = (double)xlApp.WorksheetFunction.CountA(sheet.Cells) != 0)

它抱怨试图将 != 0 比较的结果,即 bool,分配给 usedrows,即 double。使用括号将赋值结果与0进行比较:

if ((usedrows = (double)xlApp.WorksheetFunction.CountA(sheet.Cells)) != 0)

第二个错误是 .Find returns 是 Excel.Range,而不是 int。在 VBA 中,如果您将其分配给非引用类型,它将调用引用类型的默认成员。 C# 不会那样做——您必须进行显式调用。 Range 的默认成员是 .Value,但根据上下文,我假设您正在寻找行号:

var found = sheet.Cells.Find(What, After, LookIn, LookAt, SearchOrder, 
    SearchDirection, MatchCase, MatchByte, SearchFormat);
lastrow = found != null ? found.Row : 1;