如何在 VBA 中运行 Excel Add-in 中的代码

Excel Add-in 指使用 VBA 编写并且保存在 xlam 文件中的加载项(也经常被称作加载宏)。将 VBA 代码分散在各个 Excel 文件中不利于代码的管理,微软新的加载项编写技术 Web Add-in 也希望代码的部署由分散到集中。用 VBA 编写的代码,如果存放在独立的 Excel Add-in 文件中,一定程度上也是集中管理的方法。

那么,放在 xlam 的代码,其他的工作薄在 VBA 中如何调用其中的代码呢?本文做一个简单的说明。

新建一个工作簿,另存为 xlam (Excel 加载宏) 格式。Excel 对于加载宏,会默认一个存储位置,您可以手工改变存储的位置。保存在默认位置的加载宏,在 Excel Ribbon 菜单项的 开发者工具 -> 加载项 将自动出现;不在默认位置的加载宏,需要通过浏览按钮来选择。

打开 StoneUtils.xlam,在打开状态下,没有工作表,所以界面看起来是空的。通过快捷键 Alt + F11 进入 VBE 环境,插入一个模块,将模块命名为 TestModule。在 TestModule 中编写如下代码:

Public Function About() As String
    About = "Developed by Stone " & VBA.vbCrLf & " Version 1.0, 2018"
End Function

显示一条信息。

关闭加载项文件,另外打开一个 Excel 工作簿。通过 开发者工具 -> 加载项,选中 StoneUtils 加载宏:

进入 VBE 环境,我们可以看到,在左边的工程文件夹中,打开的工作表和 StoneUtils 的工程都叫 VBAProject,这可不好区分,我们需要将 StoneUtils 的 VBA Project 改一个名字。

接下来在 VBE 中添加对 StoneUtils 的引用:

然后在工作簿1中编写测试子例程如下:

Public Sub test_about_info()
    Dim info As String
    info = StoneUtils.TestModule.About()
    Debug.Print info
End Sub

运行,在立即窗口中打印出如下信息:

第二种方法,使用 Application.run():

Public Sub test_about_info_method2()
    Dim info As String
    Dim addinPath As String
    addinPath = Application.UserLibraryPath
    info = Application.Run("'" & addinPath & "StoneUtils.xlam'!About")
    Debug.Print info
End Sub

注意,工作簿文件需要用单引号包围(定界符)。第二种方法不局限于 xlam 文件,普通的 xlsm 文件也可以。

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用VBA代码Excel的图表复制到PPT。以下是示例代码: ``` Sub CopyChartsToPowerPoint() Dim pptApp As PowerPoint.Application Dim pptPres As PowerPoint.Presentation Dim pptSlide As PowerPoint.Slide Dim pptShape As PowerPoint.Shape Dim myChart As ChartObject ' Create a new instance of PowerPoint Set pptApp = New PowerPoint.Application ' Open an existing presentation or create a new one Set pptPres = pptApp.Presentations.Open("C:\Presentation1.pptx") ' Loop through all the ChartObjects in the active sheet For Each myChart In ActiveSheet.ChartObjects ' Copy the chart to the clipboard myChart.Copy ' Add a new slide to the presentation Set pptSlide = pptPres.Slides.Add(pptPres.Slides.Count + 1, ppLayoutBlank) ' Paste the chart onto the slide Set pptShape = pptSlide.Shapes.PasteSpecial(DataType:=ppPasteEnhancedMetafile) ' Set the position and size of the chart on the slide pptShape.Left = 50 pptShape.Top = 50 pptShape.Width = 500 pptShape.Height = 300 Next myChart ' Save and close the presentation pptPres.Save pptPres.Close ' Quit PowerPoint pptApp.Quit ' Clean up Set pptShape = Nothing Set pptSlide = Nothing Set pptPres = Nothing Set pptApp = Nothing End Sub ``` 这段代码会遍历当前活动工作表的所有图表,并将它们复制到一个新的幻灯片。你可以根据需要自定义位置和大小。 请注意,在运行代码之前,你需要在VBA编辑器启用对PowerPoint对象模型的引用。这可以通过选择工具->引用菜单,然后勾选“Microsoft PowerPoint XX.0 Object Library”来完成,其XX是你安装的PowerPoint版本号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值