I am working on Excel VSTO application and finding error cells in the worksheets using the below code
Excel.Range rngTemp;
Excel.Range rngErrorRange;
Excel._Worksheet Sheet1 = (Excel._Worksheet)xlCTA.Sheets["Sheet1"];
rngTemp = wsCTAWK11.UsedRange;
rngErrorRange = rngTemp.SpecialCells(Excel.XlCellType.xlCellTypeFormulas, Excel.XlSpecialCellsValue.xlErrors);
when there are really error cells found then i do not have any issues but when i dont have any error cells in these sheet i get the below exception
**threw an exception of type 'System.Runtime.InteropServices.COMException'
base {System.Runtime.InteropServices.ExternalException}: {"No cells were found."}**
How to handle this... Pls help
Catch the exception and handle it however you wish?
try
{
Excel.Range rngTemp;
Excel.Range rngErrorRange;
Excel._Worksheet Sheet1 = (Excel._Worksheet)xlCTA.Sheets["Sheet1"];
rngTemp = wsCTAWK11.UsedRange;
rngErrorRange = rngTemp.SpecialCells(Excel.XlCellType.xlCellTypeFormulas,
Excel.XlSpecialCellsValue.xlErrors);
}
catch (System.Runtime.InteropServices.COMException ex)
{
//Handle here
}
Instead of using the built in SpecialCells method write your own extension method that wraps the call to myRange.SpecialCells with error handling.
I did the following:
public static Range SpecialCellsCatchError(this Range myRange, XlCellType cellType)
{
try
{
return myRange.SpecialCells(cellType);
}
catch (System.Runtime.InteropServices.COMException ex)
{
return null;
}
}
Then you will have to account for null but it won't throw an error.
Related
I'm working on a program that allows the user to pull up part numbers from a database. The part numbers are then to be pasted into an active Excel Sheet.
I'm trying to do this with Excel interop Excel 16.0. I can copy the data but am having issues getting it to paste into excel.
private void cmdCopyToExcel_Click(object sender, EventArgs e)
{
string wb = cmb_BookName.Text.ToString();
string ws = cmb_SheetName.Text.ToString();
if (chkContainer.Checked)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks[wb];
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[ws];
xlWorksheet.Cells[48, 4] = cboContainer.Text;
}
I'm able to get the open excel workbook and worksheet that I need, but when I try to paste it into excel all I get is a COM Exception. The exception occurs on line 10. I've tried using ("wb name") and ("ws name"), have also tried using index numbers [1] for workbook and [3] for worksheets but nothing works.
Can anyone see what I'm doing wrong or is there an easier way to copy from C# and paste into an excel cell?
Addition:I tried opening the workbook that I wanted to add test to, just to see if I could get it to work.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
try
{
//create a instance for the Excel object
Excel.Application oExcel = new Excel.Application();
//specify the file name where its actually exist
string filepath = #"K:\R&D Dept\Development Lab\R&D Test Request System (For testing and training)\Test Matrices\JRD Test Matrix for part numbers.xlsm";
//pass that to workbook object
Excel.Workbook WB = oExcel.Workbooks.Open(filepath);
// statement get the workbookname
string ExcelWorkbookname = WB.Name;
// statement get the worksheet count
int worksheetcount = WB.Worksheets.Count;
Excel.Worksheet wks = (Excel.Worksheet)WB.Worksheets[3];
// statement get the firstworksheetname
string firstworksheetname = wks.Name;
//statement get the first cell value
var firstcellvalue = ((Excel.Range)wks.Cells[48, 4]).Value;
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
}
This worked, so I guess my question becomes how to work with an Excel workbook and worksheet that are already open?
I would start by getting a range of cells: i.e.{Range test = {yourWorksheet}.Cells[RowNumber, ColumnNumber]}
Once you have that, you can set the value of that cell by calling the value, or value2 property like so: {test.Value or test.Value2 = {yourPastedData}}
I'm trying to insert excel sheet data into a DB using Lists.in. In the excel data I have some empty cells. Because of the empty cells I am getting errors like Cannot perform runtime binding on a null reference. How can I solve this error? Thanks.
I tried this code:
public object verify(object k)
{
try
{
if (range.Cells[rCnt, 3] == null)
{
return range.Cells[rCnt, 3].value="null";
}
}
catch
{
return k;
}
}
but it shows an error at method name.
Iterating over all sheets in a Spreadsheet I ran into this error message:
Unable to cast transparent proxy to type 'Microsoft.Office.Interop.Excel.Worksheet'.
This spreadsheet has some chart tabs that obviously cant be cast to a sheet. So when I run this code I get the above error:
foreach (Microsoft.Office.Interop.Excel.Worksheet activeSheet in xlApp.Sheets)
{
}
I've looked around to find a solution and a few people have encountered it - in different scenario's to me eg:
http://social.msdn.microsoft.com/forums/en-US/vsto/thread/ab2e917a-d3bf-4e6a-84dc-7f8a9440fe0a
I am not happy with the workaround I have so far. I feel that exceptions should be used exceptionally and this isn't one of those places:
for (int i = 0; i < xlApp.Sheets.Count; i++)
{
try
{
Worksheet wk = (Worksheet)xlApp.Sheets[i];
}
catch (Exception)
{
//This isn't a sheet - avoid sheet operations
}
}
I'm wondering if anyone knows how to iterate through the Sheets (skipping non-sheets) without the need for a Try-Catch? Is there some method or property in the Excel object model that can tell you if a sheet is not really a sheet?
What about:
foreach (object possibleSheet in xlApp.Sheets)
{
Microsoft.Office.Interop.Excel.Worksheet aSheet = possibleSheet as Microsoft.Office.Interop.Excel.Worksheet;
if (aSheet == null)
continue;
// your stuff here
}
Of course it would work only if you get the exception only for the chart tabs and not for the other sheets.
There's something weird about get_Caller(Type.Missing) method. It returns a negative integer, -2146826265, instead of the Range object as it should.
Has anyone come across this issue before? Why is that and how should I solve it?
Thanks.
Excel.Range range = (Excel.Range) application.get_Caller(System.Type.Missing);
The above code would fail if I try to explicitly user type Excel.Range. The error message says, 'Cannot convert type 'int' to 'Microsoft.Office.Interop.Excel.Range'.
EDIT:
The intention of getting caller of the cell is to pass it to my following function:
private string getResultFromResultSheet(Excel.Range originalSheetRange, Excel.Worksheet resultSheet)
{
string DataResult = "";
try
{
string os_currentAddress = originalSheetRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
Excel.Range currentRRange = null;
currentRRange = resultSheet.get_Range(os_currentAddress, Type.Missing);
if (currentRRange != null)
{
if (string.IsNullOrEmpty(Convert.ToString(currentRRange.Value)))
DataResult = "";
else
DataResult = Convert.ToString(currentRRange.Value);
}
}
catch (Exception ex)
{
}
return DataResult;
}
With the return value from that function, I can pass it back to UDF and display it in the original cell. Is there any better way to implement the function?
Review the table at the end of this MSDN Library article about the Application.Caller property. You've discovered the value of the #REF! error. Google 'excel error 2023' for additional info. I kinda doubt you can use this property, given that the caller is your C# program.
I am attempting what seems like a simple task: using C# to create a new Excel document containing new worksheets.
For some reason, I am getting a strange COM error (0x800A03EC)
Has anyone managed to get this to work? Does anyone have suggestions as to how to troubleshoot this?
I've isolated this into the minimum amount of code:
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
namespace ExcelAutomation
{
public static class ExcelTests
{
public static void CreateWorksheet()
{
try
{
var app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
var workBooks = app.Workbooks;
var newWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet existingWorksheet = (Worksheet)newWorkbook.Sheets[1];
Worksheet workSheet = (Worksheet)newWorkbook.Sheets.Add
(
null, // before
existingWorksheet,
null, // 1,
null //XlSheetType.xlWorksheet
);
}
catch (System.Runtime.InteropServices.COMException ex)
{
Trace.WriteLine(string.Format("Caught COMException. Message: \"{0}\"", ex.Message));
}
}
}
}
The output window now says:
Caught COMException. Message: "Exception from HRESULT: 0x800A03EC"
The mistake I'm making is to use null for optional values that I don't want to set.
Instead I should use System.Reflection.Missing.Value
Worksheet workSheet = (Worksheet)newWorkbook.Sheets.Add
(
existingWorksheet, // before
System.Reflection.Missing.Value,
System.Reflection.Missing.Value, // 1,
System.Reflection.Missing.Value //XlSheetType.xlWorksheet
);
I Think this will help you
Visit http://www.aspose.com/docs/display/cellsnet/Adding+New+Worksheets+to+Workbook+and+Activating+a+Sheet