我有以下代码将值写入excel中的activecell。它可以在50%的时间内正常工作,但不是最后的50%。 为什么?
void ValueToExcel(string value)
{
Excel.Application oXL=null;
Excel.Workbook oWB=null;
Excel.Worksheet oSheet=null;
Excel.Range rng =null;
try
{
oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
oXL.Visible = true;
oWB = (Excel.Workbook)oXL.ActiveWorkbook;
oSheet = oWB.ActiveSheet;
rng = oSheet.Application.ActiveCell;
rng.Value = value;
rng.Application.ActiveCell.Offset[1, 0].Select();
}
catch (Exception EX)
{
MessageBox.Show(EX.Message);
}
}
我尝试更改代码,但仍无效。似乎该值被写入其他一些Excel应用程序。
void ValueToExcel(string value)
{
//Gets Excel and gets Activeworkbook and worksheet
Excel.Application oXL=null;
Excel.Workbook oWB=null;
Excel.Worksheet oSheet=null;
Excel.Range rng =null;
try
{
while (oXL==null)
oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
oXL.Visible = true;
while (oWB == null)
oWB = (Excel.Workbook)oXL.ActiveWorkbook;
while (oSheet == null)
oSheet = oWB.ActiveSheet;
while (rng == null)
rng = oSheet.Application.ActiveCell;
while(rng.Value=="")
rng.Value = value;
MessageBox.Show(value);
Console.Beep();
rng.Application.ActiveCell.Offset[1, 0].Select();
}
catch (Exception EX)
{
MessageBox.Show(EX.Message);
}
}
有人帮忙吗?