Excel的二次开发有一极大的优势所在,可以结合用户的交互进行程序的运行,大量用户的交互,都是从选择对象开始,用户选择了单元格区域、图形、图表等对象,之后再进行程序代码的加工处理,生成用户所需的最终结果。
所以熟练处理选择对象,尤其关键,而在VBA里的使用方法,来到.Net中特别是C#语言下,就需要另外的代码处理,希望此篇的分享给VBA转VSTO的朋友们带来一些帮助指引。
在VBA中,判断一个Selection对象是什么类型的方法如下:
Sub test() Dim sel Set sel = Selection If TypeOf sel Is Range Then Debug.Print 1 End If End Sub
在C#中,想引用TypeOf方法,就要引用VisualBasic的Dll,麻烦,其实在C#里,可以直接用 is 和 as 的语句来实现此类的判断。
结合Excel催化剂开发的判断选中Selection是区域还是形状来做图形调整的功能,给大家分享下源代码。
此代码中,用户选定的Selection对象,有三类
public static DictionaryGetShpInfos() { Excel.Range selRange = Common.ExcelApp.Selection as Excel.Range; Dictionary dicShpInfo = new Dictionary (); if (selRange != null) { dicShpInfo = GetShpInfoBySelectRange(selRange); } else { Excel.DrawingObjects drawingObjects = Common.ExcelApp.Selection as Excel.DrawingObjects; if (drawingObjects != null) { int shpCount = drawingObjects.ShapeRange.Count; for (int i = 1; i <= shpCount; i++) { Excel.Shape shp = drawingObjects.ShapeRange.Item(i); dicShpInfo.Add(shp, shp.TopLeftCell.MergeArea); } } else { Excel.Worksheet actSht = Common.ExcelApp.ActiveSheet; var selShp = Common.ExcelApp.Selection; foreach (Excel.Shape shp in actSht.Shapes) { if (shp.Name == selShp.Name && shp.TopLeftCell.Address == selShp.TopLeftCell.Address && shp.BottomRightCell.Address == selShp.BottomRightCell.Address) { dicShpInfo.Add(shp, shp.TopLeftCell.MergeArea); } } } } return dicShpInfo; } private static Dictionary GetShpInfoBySelectRange(Excel.Range selRange) { Excel.Worksheet actSht = selRange.Parent; Dictionary dicShpInfo = new Dictionary (); if (selRange.Cells.Count > 1) { foreach (Excel.Shape shp in actSht.Shapes) { Excel.Range topLeftCell = shp.TopLeftCell; Excel.Range bottomRightCell = shp.BottomRightCell; Excel.Range shpRange = actSht.Range[topLeftCell, bottomRightCell]; if (Common.ExcelApp.Intersect(shpRange, selRange) != null) { dicShpInfo.Add(shp, shp.TopLeftCell.MergeArea); } } } else { foreach (Excel.Shape shp in actSht.Shapes) { dicShpInfo.Add(shp, shp.TopLeftCell.MergeArea); } } return dicShpInfo; }
结语
不积跬步无以至千里,Excel催化剂的大量功能,都是一点一滴地开发出来的,但愿这些开发过程中遇到的小细节,小坑小洼的分享,能够带给广大后来学习者一些指引。
页面更新:2024-02-14
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号