Я перемещаю свой код VBA в проект надстройки C# VSTO Excel в VS2019. Сегодня возникла одна проблема: WorksheetFunction.Countif испортил цикл FOR. В самом начале выскочила ошибка "OleAut сообщил о несоответствии типов". Почему-то я больше не мог повторить эту ошибку. Но я знаю, что проблема все еще существует. Пожалуйста помоги. Спасибо. Вот код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Runtime.InteropServices;
public void Validate_Tags1()
{
//If found the invalid data, highlight it.
Boolean fDup = false, fSpare, fTBD = false, fSChar = false, fEmptyTag = false, fInvIOType = false, fInvTag;
Excel.Workbook wbk = Globals.ThisAddIn.Application.ActiveWorkbook;
Excel.Worksheet wsh = wbk.Worksheets[1];
Excel.Range rng;
Regex keywrd;
int intRowIO = wsh.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
rng.Interior.Color = System.Drawing.Color.White;
//Loop through each tag in the Column 3. Spare channels are filtered out. Invalid cell will be red highlighted.
foreach (Excel.Range rngCell in rng)
{
string strtag = rngCell.Value2;
//Check if the tag cell is empty
if ((strtag is null) || (strtag == ""))
{
fEmptyTag = true;
rngCell.Interior.Color = System.Drawing.Color.Red;
}
else
{
//Check if tag is still "To Be Determined"
keywrd = new Regex("TBD", RegexOptions.IgnoreCase);
Boolean fTBDTag = false;
if (keywrd.IsMatch(strtag))
{
fTBD = true;
fTBDTag = true;
rngCell.Interior.Color = System.Drawing.Color.Red;
}
//Check if the tag is duplicated.
keywrd = new Regex("spare", RegexOptions.IgnoreCase);
fSpare = keywrd.IsMatch(strtag);
if (!fSpare && !fTBDTag)
{ listbox1.items.add("Row " + rngCell.Row + ": Found no issue.");
// I had to comment out the following lines to get the FOR loop completed. If put the
//codes back, the Messagebox on the last line won't pop out.
//if (ExcelApp.WorksheetFunction.CountIf(rng, rngCell.Value2) > 1)
//{
// fDup = true;
// rngCell.Interior.Color = System.Drawing.Color.Red;
//}
}
}
}
messagebox.show("Done!");
}
С показанным кодом вам не хватает объявления для ExcelApp
Попробуйте добавить эту строку в начало кода:
var ExcelApp = Globals.ThisAddIn.Application;