从不同的工作簿调用Excel宏 [英] Call an Excel macro from a different Workbook

查看:347
本文介绍了从不同的工作簿调用Excel宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作簿HasMacros.xlsm和一个工作簿HasData.xlsm



在HasMacros.xlsm中,我添加了一个名为Mod1的模块,并且只有这个代码:

  Sub testmacro()

MsgBox(Test)

结束Sub

在HasData.xlsm中,我添加了一个名为Mod2的模块,并且只有这个代码: p>

  Sub testmacro2()

'XXX

End Sub

到目前为止,很好。



现在,我想从testmacro2中调用testmacro,其中写入XXX。



这会导致立即编译错误:

  Sub testmacro2()

testmacro()

End Sub

在exec上编译错误Sub of function not defined

  Sub testmacro2()

调用testmacro

End Sub

无法立即编译错误:

  Sub testmacro2()

Mod1.testmacro()

End Sub

在exec上失败:



Sub testmacro2()



调用Mod1.testmacro



End Sub



然后,我尝试了如何从VBA中的另一个特定工作簿调用函数? a>但是我得到


与现有模块,项目或对象库的名称冲突


我已经完成了关于如何从HasData.xlsm中的VBA代码中调用HasMacros.xlsm中的宏的想法

您还可以将 Workbook HasMacros.xlsm 中的VBA项目的名称更改为 VBAProject ,然后从HasData.xlsm项目中设置一个引用(VB编辑器中的工具 - 引用)到该项目。那将允许您直接调用其他宏,而不使用运行


I have a Workbook HasMacros.xlsm and a Workbook HasData.xlsm

In HasMacros.xlsm I add a Module named Mod1 with exactly this and only this code:

Sub testmacro()

   MsgBox ("Test")

End Sub

In HasData.xlsm I add a Module named Mod2 with exactly this and only this code:

Sub testmacro2()

   'XXX

End Sub

So far, so good. Nothing else opened in Excel.

Now, I want to call testmacro from testmacro2 where XXX is written.

This fails with immediate compilation error:

Sub testmacro2()

   testmacro()

End Sub

This fails with compilation error "Sub of function not defined" on exec:

Sub testmacro2()

   Call testmacro

End Sub

This fails with immediate compilation error:

Sub testmacro2()

   Mod1.testmacro()

End Sub

This fails on exec:

Sub testmacro2()

Call Mod1.testmacro

End Sub

Then, I tried How to call function from another specific workbook in VBA? but I get

Name conflicts with existing module, project, or object library

I've run out of ideas at all about how to call a macro in HasMacros.xlsm from VBA code in HasData.xlsm

解决方案

You can also change the name of the VBA project in Workbook HasMacros.xlsm to something other than VBAProject and then set a reference (Tools - References in the VB Editor) to that project from the HasData.xlsm project. That will then allow you to directly call the other macro without using Run.

这篇关于从不同的工作簿调用Excel宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆