ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 Excel Home精品图文教程库
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
300集Office 2010微视频教程 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 26304|回复: 33

**给Excel VBA开外挂** 最快捷的保护代码方法-- 用ExcelDna建立自定义函数(XLL加载宏)

  [复制链接]

TA的精华主题

TA的得分主题

发表于 2012-12-2 21:23 | 显示全部楼层 |阅读模式
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
本帖已被收录到知识树中,索引项:插件开发
本帖最后由 liucqa 于 2012-12-29 23:24 编辑

忙活3天,俺终于解决了在C#里面的XLL加载宏调用工作表函数、自定义函数的注册和反注册问题,全靠C API
使用xll加载宏作一机一码及封装工作表函数的演示,保护源代码,方便授权

****************************************************************

一般来说,建立xll加载宏之后,可以很方便的直接调用里面的函数了(相当于多了自定义函数的功能
但是,一般来说,建立xll加载宏需要使用C/C++来编写代码,开发耗时长,有没有一种简单的直接通过C#源文件来快速开发XLL呢?

在某大神的推荐下,我试用了ExcelDna开源项目,发现使用该项目可以很轻松的通过C#源代码来直接建立XLL文件,其过程与VBA开发类似(都是直接编辑源文件即可),无需开发者考虑具体的XLL接口的代码规则编写。

下面的附件是一个通过ExcelDna打包的XLL加载宏(获取字符串的hash512bit值),可以直接在工作表或VBA中使用。
VBA中的调用方法:
1、打开加载宏
2、新建工作簿

在vba模块中使用下面的语句调用:
  1. Sub test()
  2.     MsgBox Application.Run("SHA", "my string")
  3.     MsgBox Application.ExecuteExcel4Macro("SHA(""my string"")")
  4. End Sub
复制代码
exceldna-packed.rar (118.72 KB, 下载次数: 634)


具体开发和打包的过程,见下帖
http://club.excelhome.net/thread-951893-1-1.html

该方法可以使开发者方便的在vba中调用C#、VB、F#里面丰富的类资源,极大的扩展了vba的使用范围。值得大家尝试。

直接通过修改.dna文件建立的加载宏,代码安全并没有得到保障,只是开发的速度快很多。
如果需要保护你的源码,则需要使用C#建立你自己的XLL文件



更专业的使用方法见5楼

评分

2

查看全部评分

TA的精华主题

TA的得分主题

发表于 2012-12-2 21:38 | 显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
去研究一下

TA的精华主题

TA的得分主题

 楼主| 发表于 2012-12-2 21:30 | 显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
本帖最后由 liucqa 于 2018-11-29 02:01 编辑

https://www.bilibili.com/video/av34439971/ 这有视频教程

TA的精华主题

TA的得分主题

 楼主| 发表于 2012-12-2 21:32 | 显示全部楼层
Getting started with Excel-DNA
==============================

Do this first:
--------------

* The .NET 2.0 runtime must be installed (or .NET 4 with additional settings).
The .NET Framework Version 2.0 Redistributable Package is available from Microsoft here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=0856eacb-4362-4b0d-8edd-aab15c5e04f5&DisplayLang=en

* Macros security in Excel must not be 'Very High' or 'High' (if set to Medium -- it will prompt whether to enable each macro library). To use the .NET macros you will have to 'Enable' at the prompt.


1. Create a user-defined function in Visual Basic
-------------------------------------------------
* Make a copy of ExcelDna.xll in a convenient directory, calling the copy Test1.xll.
* Create a new text file, called Test1.dna (the same prefix as the .xll file), with contents:

        <DnaLibrary>
        <![CDATA[
       
                Public Module MyFunctions

                                Function AddThem(x, y)
                                                AddThem = x + y
                                End Function       

                End Module
               
        ]]>
        </DnaLibrary>
       
* Load Test1.xll in Excel (either File->Open or Tools->Add-Ins and Browse).
* You should be prompted whether to Enable Macros, click Enable.
* Enter =AddThem(4,2) into a cell - you should get 6.
* There should also be an entry for AddThem in the function wizard, under the category Test1.

Troubleshooting
---------------
* If you are not prompted to Enable Macros and nothing else happens, your security level is probably on High. Set it to Medium.
* If you get a message indicating that the .xll file is not recognized (and even opening it as text), you might not have the .NET Framework 2.0 installed. Install it. Otherwise Excel is using .Net version 1.1 by default. To change this, refer back to the prerequisites section.
* If Excel crashes with an unhandled exception, an access violation or some other horrible error, either during loading or when running the function, please let me know. This shouldn't happen, and I would like to know if it does.
* If a form appears with the title 'ExcelDna Compilation Errors' then there were some errors trying to compile the code in the .dna file. Check that you have put the right code into the .dna file.
* If Excel prompts for Enabling Macros, and then the function does not work and does not appear in the function wizard, you might not have the right filename for the .dna file. The prefix should be the same as the .xll file and it should be in the same directory.
* Otherwise, if something goes wrong, let me know.

2. Creating a user-defined function in C#
-----------------------------------------
* Change the contents of Test1.dna to:

<DnaLibrary Language="CS">
        <![CDATA[
       
          using ExcelDna.Integration;
       
                public class MyFunctions
                {
                        [ExcelFunction(Description="Joins a string to a number", Category="Useful functions")]
                        public static string JoinThem(string str, double val)
                        {
                                return str + val;
                        }
                }
               
        ]]>
</DnaLibrary>

* Reload the .xll, either from File->Open or in Tools->Add-Ins.
* Check with the formula =JoinThem("abc", 123)
* If the first example worked, this one should too.

3. Making the functions from a compiled library available
---------------------------------------------------------
ExcelDna can also load any compiled .NET library. Public static functions with a compatible signature are exported to Excel.

* Create a file called TestLib.cs containing the following code:

        using ExcelDna.Integration;
       
        public class SomeClass
        {

            [ExcelFunction(Description="Multiplies two numbers", Category="Useful functions")]
            public static double MultiplyThem(double v1, double v2)
            {
                return v1 * v2;
            }
        }


* Compile TestLib.cs to TestLib.dll: from the command-line:
c:\windows\microsoft.net\framework\v2.0.50727\csc.exe /target:library /reference:ExcelDna.Integration.dll TestLib.cs

* Modify Test1.dna to contain:

        <DnaLibrary>
                <ExternalLibrary Path="TestLib.dll" />
        </DnaLibrary>

* Reload the .xll and check =MultiplyThem(2,3)
* To support .NET 4 assemblies, add a RuntimeVersion="v4.0" attribute to the DnaLibrary tag:

        <DnaLibrary RuntimeVersion="v4.0">
                <ExternalLibrary Path="TestLib.dll" />
        </DnaLibrary>


4. Additional samples
---------------------
Included in the distribution is a file, MoreSamples.dna, containing samples of Excel integration and showing more of the functionality of ExcelDna. To use it, make a copy of ExcelDna.xll called MoreSamples.xll (matching the .dna name), and open MoreSamples.xll in Excel.

TA的精华主题

TA的得分主题

 楼主| 发表于 2012-12-3 00:30 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
本帖最后由 liucqa 于 2012-12-3 00:56 编辑

使用ExcelDna建立加载宏的一个具体示例

给Excel增加获取硬件参数的函数

先运行.xll文件,启动加载宏。然后打开.xlsx文件


效果如图:
捕获.JPG

TA的精华主题

TA的得分主题

 楼主| 发表于 2012-12-3 00:40 | 显示全部楼层
本帖最后由 liucqa 于 2012-12-29 22:08 编辑

具体步骤:

参考提供的CS样本例子,我通过VS项目工程,建立了需要的xll文件和DLL文件,并使用ExcelDnaPack.exe工具打包成一个.xll加载宏。

具体步骤:
1、打开样本工程CSharpAddIn.sln
2、添加引用System.Management.DLL
3、编辑代码(写成public static函数就行)
4、修改SampleCS.dna的内容为:
  1. <DnaLibrary Name="Sample Excel-DNA Library in C#" RuntimeVersion="v4.0">
  2.     <ExternalLibrary Path="CSharpAddIn.dll" Pack="true" />
  3. </DnaLibrary>
复制代码
5、编译生成DLL
6、copy ExcelDna.Integration.dll、ExcelDnaPack.exe、VS工程生成的四个文件(CSharpAddIn.dll、CSharpAddIn.pdb、SampleCS.dna、SampleCS.xll)到一个目录内
7、在DOS窗口下,进入该目录,执行  ExcelDnaPack  SampleCS.dna,得到打包之后的文件:SampleCS-packed.xll

使用该文件作为加载宏启动之后,即可在Excel中调用你自己的自定义函数了。

使用此种方法建立的XLL文件,由于是调用CS生成的DLL来提供函数,因此代码的安全性有一定保证。

打包之后的XLL加载宏
SampleCS-packed.rar (126.34 KB, 下载次数: 325)

需要.net 4.0支持,请自行安装







TA的精华主题

TA的得分主题

 楼主| 发表于 2012-12-3 12:36 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
本帖最后由 liucqa 于 2012-12-29 22:10 编辑

测试发现,先启动xlsx,后启动xll,excel会自动更新自定义函数的值。反过来不更新。

F9刷新对xll的自定义函数无效。


***************************

原因:默认是非易失性函数,可以修改此参数




TA的精华主题

TA的得分主题

发表于 2012-12-22 16:53 | 显示全部楼层
why?
untitled.JPG

点评

要安装.net 4.0.C#是托管代码,需要.net环境支持  发表于 2012-12-22 17:28

TA的精华主题

TA的得分主题

发表于 2012-12-29 21:36 | 显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
本帖最后由 engineerlzk 于 2013-1-1 19:20 编辑

谢谢,学习了!留个记号

TA的精华主题

TA的得分主题

发表于 2013-1-22 09:51 | 显示全部楼层
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

关闭

最新热点上一条 /1 下一条

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-4-20 14:41 , Processed in 0.051830 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表