ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

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

[分享] vba里使用.net类

[复制链接]

TA的精华主题

TA的得分主题

发表于 2024-5-13 13:18 | 显示全部楼层 |阅读模式
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
本帖最后由 fxl447098457 于 2024-5-13 13:24 编辑

分享一个自己保存的经典模块。今天整理下资料给vber/vbaer瞧上一瞧。附件示例通过引用common language runtime execution engine 和mscorlib.dll以及相关类模块打通vba和.net壁垒.手段也比曾经我通过powershell去调用.net里的类要优雅得多。我相信会为vber/vbaer打开一扇新的大门。附件里展示了一个vba里使用c#的正则demo。wps(x86)/office 365(x64)测试均通过。
vba使用.net.xlsm.7z (70.98 KB, 下载次数: 76)

评分

6

查看全部评分

TA的精华主题

TA的得分主题

发表于 2024-5-13 19:23 | 显示全部楼层

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-14 10:08 | 显示全部楼层
因为这个源码是通过反射实现的,这就和com里的后期绑定那样,没那么友好。其实你上面的帖子里代码我转换到这个里面也一样可以实现,顺便打印了一下图片的宽高度。代码如下:
Sub test1()
    Dim host As New CLRHost, inputFile$, outputFile$
    Call host.Initialize(False)
    inputFile = ThisWorkbook.Path & "\1.emf"
    outputFile = ThisWorkbook.Path & "\1.png"
    On Error Resume Next
    Dim asmSys As mscorlib.Assembly
   Set asmSys = host.CLRLoadAssembly("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
   Dim imgclass As mscorlib.Object, img As mscorlib.Object, fmt As mscorlib.Object, png As mscorlib.Object
   Set imgclass = host.CLRResolveType("System.Drawing.Image")
   Set img = host.CLRInvokeStaticMethod(imgclass, "FromFile", inputFile)
    Debug.Print "图片高度: "; host.CLRProperty(img, "Height"); "图片宽度:"; host.CLRProperty(img, "Width")
   Set fmt = host.CLRResolveType("System.Drawing.Imaging.ImageFormat")
   Set png = host.CLRInvokeMethod(host.CLRInvokeMethod(fmt, "GetProperty", "Png"), "GetValue", Null)
   host.CLRInvokeMethod img, "Save", outputFile, png
   Set imgclass = Nothing
   Set img = Nothing
   Set fmt = Nothing
   Set png = Nothing
   Set host = Nothing
End Sub

评分

1

查看全部评分

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-16 21:07 | 显示全部楼层
Sub 获取压缩包列表()
'这个例子至少需要.net 4.5才能支持
'System.IO.Compression.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Dim host As New CLRHost, zipfilepath As String
Call host.Initialize(False)
'On Error Resume Next
Dim asmSys As mscorlib.Assembly, ZipFile As mscorlib.Object, archive As mscorlib.Object, Entries As Variant, entry As Variant
Set asmSys = host.CLRLoadAssembly("System.IO.Compression.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
Set ZipFile = host.CLRResolveType("System.IO.Compression.ZipFile")
zipfilepath = "C:\Users\Administrator\Downloads\Compressed\pcre2-10.43.zip"
If Len(Dir(zipfilepath)) = 0 Then MsgBox "所在路径的zip压缩包不存在": Exit Sub
Set archive = host.CLRInvokeStaticMethod(ZipFile, "OpenRead", "C:\Users\Administrator\Downloads\Compressed\pcre2-10.43.zip")
Set Entries = host.ToEnumerable(host.CLRProperty(archive, "Entries"))
For Each entry In Entries
    Debug.Print host.CLRProperty(entry, "FullName")
Next
    Set archive = Nothing
    Set ZipFile = Nothing
    Set host = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-16 21:09 | 显示全部楼层
Sub 使用随机数()
Dim host As New CLRHost, dic As Object, s As Long, key As Variant
Dim objRandom As mscorlib.Object, asmSys As mscorlib.Assembly
Call host.Initialize(False)
Set dic = CreateObject("scripting.dictionary")
Set asmSys = host.CLRLoadAssembly("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    Set objRandom = host.CLRCreateObject("System.Random")
    ' 使用「System.Random.Next(Int32, Int32)」
    '生成十个不重复随机数
    Do
        s = host.CLRInvokeMethod(objRandom, "Next")
        If Not dic.Exists(s) Then dic.Add s, ""
    Loop Until dic.Count >= 10
    For Each key In dic.Keys
        Debug.Print key
    Next key
    Set dic = Nothing
    Set objRandom = Nothing
    Set host = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-22 08:12 | 显示全部楼层
Sub filetext() '写入文本
Dim host As New CLRHost, Encoding As mscorlib.Object, utf8 As mscorlib.Object, textPath$, createText$
Call host.Initialize(False)
'On Error Resume Next
Dim asmSys As mscorlib.Assembly, SW As mscorlib.Object, writer As mscorlib.Object
host.CLRLoadAssembly ("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
host.CLRLoadAssembly ("System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
host.CLRLoadAssembly ("System.Text.Encoding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

Set SW = host.CLRResolveType("System.IO.Stream")
Set Encoding = host.CLRResolveType("System.Text.Encoding")
Set utf8 = host.CLRInvokeMethod(host.CLRInvokeMethod(Encoding, "GetProperty", "UTF8"), "GetValue", Null)
textPath = ThisWorkbook.Path & "\CDriveDirs.txt"
Set writer = host.ToObject(host.CLRGetType(SW).Assembly).CreateInstance_3("System.IO.StreamWriter", False, BindingFlags_Instance Or BindingFlags_Public Or BindingFlags_CreateInstance, Nothing, Array(textPath, False, utf8), Nothing, Array())
createText = "Hello and Welcome,热烈欢迎"
host.CLRInvokeMethod writer, "Write", createText  '此excel所在路径文件夹会生成一个CDriveDirs.txt,并写入utf8文本with BOM
host.CLRInvokeMethod writer, "Close"
Set SW = Nothing
Set writer = Nothing
Set Encoding = Nothing
Set utf8 = Nothing
Set host = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-22 08:13 | 显示全部楼层
Sub filetextReader() '读入文本
Dim host As New CLRHost, Encoding As mscorlib.Object, utf8 As mscorlib.Object, textPath$, readText$
Call host.Initialize(False)
'On Error Resume Next
Dim asmSys As mscorlib.Assembly, SW As mscorlib.Object, reader As mscorlib.Object
host.CLRLoadAssembly ("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
host.CLRLoadAssembly ("System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
host.CLRLoadAssembly ("System.Text.Encoding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
textPath = ThisWorkbook.Path & "\CDriveDirs.txt"
If Len(Dir(textPath)) = 0 Then MsgBox "先执行上面的写入文本操作再来读取文本.": GoTo label:
Set SW = host.CLRResolveType("System.IO.Stream")
Set Encoding = host.CLRResolveType("System.Text.Encoding")
Set utf8 = host.CLRInvokeMethod(host.CLRInvokeMethod(Encoding, "GetProperty", "UTF8"), "GetValue", Null)
Set reader = host.ToObject(host.CLRGetType(SW).Assembly).CreateInstance_3("System.IO.StreamReader", False, BindingFlags_Public Or BindingFlags_Instance Or BindingFlags_CreateInstance, Nothing, Array(textPath, utf8), Nothing, Array())
readText = host.CLRInvokeMethod(reader, "ReadToEnd")
host.CLRInvokeMethod reader, "Close"
Debug.Print readText
label:
Set SW = Nothing
Set reader = Nothing
Set Encoding = Nothing
Set utf8 = Nothing
Set host = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-22 08:14 | 显示全部楼层
'.net version 3.5 not necessary
Sub ssortedlist()
Dim host As New CLRHost
Call host.Initialize(False)
Dim Assem As mscorlib.Assembly, mySL As Object, Total%, i%, aList As Object, interfacelist As Object
host.CLRLoadAssembly ("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
Set Assem = host.CLRLoadAssembly("System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
Set mySL = host.ToObject(host.CLRCreateObject("System.Collections.SortedList"))
mySL.Add "Third", "!"
mySL.Add "Second", "World"
mySL.Add "First", "Hello"
Total = mySL.Count
Debug.Print "个数:", Total
For i = 0 To Total - 1
Debug.Print mySL.GetKey(i), mySL.GetByIndex(i)
Next

Set mySL = Nothing
Stop
Set aList = host.ToObject(host.CLRCreateObject("System.Collections.ArrayList"))
aList.Add ("Hello")
aList.Add ("World")
aList.Add ("!")
For Each key In aList
Debug.Print key
Next key
Debug.Print aList.IndexOf("!", 0)
Set aList = Nothing
Set host = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2024-5-22 08:15 | 显示全部楼层
Sub stringbuildtest()
'.net version 3.5 not necessary
Dim host As New CLRHost
Call host.Initialize(False)
Dim Assem As mscorlib.Assembly, sb As mscorlib.Object, r As Variant
host.CLRLoadAssembly ("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
Set sb = host.ToObject(host.CLRCreateObject("System.Text.StringBuilder"))
   Set sb = host.CLRInvokeMethod(sb, "Append", "The quick brown fox jumped over the lazy dog. ")
   Set sb = host.CLRInvokeMethod(sb, "Append", "Mary had a little lamb.")
   Debug.Print host.CLRProperty(sb, "Length")
    r = host.CLRInvokeMethod(sb, "ToString")
    Debug.Print r
    Set sb = Nothing
     Set host = Nothing
End Sub

TA的精华主题

TA的得分主题

发表于 2024-7-13 07:42 来自手机 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
可以加载自己用c#写的dll吗?
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

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

GMT+8, 2024-11-19 11:16 , Processed in 0.050362 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

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

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

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