|
本帖最后由 yizckzhou 于 2020-6-3 16:48 编辑
场景:自定义函数所在单元格显示标题字符串,触发事件后在该单元格下展示数据(如图)
问题:数据展示成功后,在函数单元格再次回车,获取不到cell的formulaArray等各属性,即再次调用该方法后,string lsFormula = xlRange.FormulaArray.ToString();//此处获取不到内容了,希望能人指教,谢谢
C#代码如下:
/// <summary>
/// 计算时触发
/// </summary>
/// <param name="thesh"></param>
private void OnCalculate(Worksheet thesh)
{
try
{
if (Globals.ThisAddIn.Application.ActiveCell == null) return;//初始未有单元格,忽略
Range xlRange = (Globals.ThisAddIn.Application.ActiveCell as Range).CurrentRegion;//获取当前单元格
string lsFormula = xlRange.FormulaArray.ToString();//函数内容
if (lsFormula.Contains("Pms"))
{
if (!CheckLogin())
{
xlRange.Value = string.Empty;
return;
}
//定位此时的单元格位置
int lsCurrentR = xlRange.Row;
int lsCurrentC = xlRange.Column;
string lsMsg = string.Empty;
//函数信息截取
string lsFuncName = lsFormula.Substring(0, lsFormula.IndexOf("(")).TrimStart('=');
string lsParamAll = lsFormula.Substring(lsFormula.IndexOf("(") + 1).TrimEnd(")".ToArray());
//参数截取
string[] lisParams;
PmsData pdTmp = new PmsData();
bool isNeedParm = pdTmp.IsNeedParm(lsFuncName, out lsMsg);//判断是否需要参数
if (lsMsg.Length > 0)
{
MessageUtil.ShowTips(lsMsg);
return;
}
if (lsParamAll.Trim().Length > 0 && isNeedParm)//获取函数的参数集合
lisParams = GetParams(lsParamAll.Split(','), thesh);
else
lisParams = lsParamAll.Split(',');
//数据调用
System.Data.DataTable dtResult = pdTmp.GetPmsData(lsFuncName, out lsMsg, lisParams);
if ((dtResult == null || dtResult.Rows.Count == 0) && lsMsg.Length > 0)
{
MessageUtil.ShowTips(lsMsg);
return;
}
for (int i = 0; i < dtResult.Rows.Count; i++)
{
for (int j = 0; j < dtResult.Columns.Count; j++)
{
if (i == 0)//赋值表格标题
thesh.Cells[i + lsCurrentR + 1, j + lsCurrentC] = dtResult.Columns[j].Caption;
//赋值表格数据
thesh.Cells[i + lsCurrentR + 2, j + lsCurrentC].Value = dtResult.Rows[j].ToString();
//单元格样式,值调整
fsc.SetRangeStyle(lsFuncName, dtResult.Columns[j].ColumnName, thesh.Cells[i + lsCurrentR + 2, j + lsCurrentC], dtResult.Rows[j]);
}
}
lsFormula = xlRange.FormulaArray.ToString();//赋值操作后,此处就已经无法再次获取到
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
|
|