【问题标题】:VBA: Conditional compilation with implements keywordVBA:使用 implements 关键字进行条件编译
【发布时间】:2015-03-02 16:54:25
【问题描述】:

是否可以将编译器条件常量与“implements”关键字一起使用,其中接口位于加载项中?

我的工作簿的类模块中有以下内容,我们称之为book1:

#Const Condition1 = 0 ''will be replaced with 1 when add-in is opened
#if Condition1 then
    Implements myAddIn.iInterfaceFoo
#End if

我将加载项 myAddIn 列为参考(即在工具 -> 参考...中)。

我在加载项中成功使用了该接口与其他类,但现在我想直接在我的工作簿 book1 中调用该接口。只要加载项打开,当我编译 book1(即 Debug -> Compile VBAProject)时,它就会编译成功。

但是,当我尝试在加载项关闭的情况下编译 book1 时,出现错误

Compile error: User-defined type not defined

这正是我要避免的 - 否则,如果插件丢失(例如在其他人的计算机上),电子表格本身仍然可以工作。

【问题讨论】:

  • 感谢您的反馈,我已尝试改进问题。我已经实例化了该类,但这是编译器错误而不是运行时错误。感谢implements 上的链接,但我对它的工作方式很满意 :)
  • 好吧,当Condition1 为假时,您的代码甚至不应该尝试编译Implements myAddIn.iInterfaceFoo。您是否在将 Condition1 设置为 true/false 时遇到问题,具体取决于加载项是否已加载?可能会看到thisthat
  • 就是这样 - 它确实会尝试编译 Implements 行,即使 Condition1False。我会看看那些链接的答案。
  • 这是一种相当奇怪的行为。我无法重现这一点。对我来说,当条件为假时,Implements 不会被编译。
  • @MichaelChad,不,我没有,我更改了工作簿中的代码,因此我只在sub 中调用插件,而不是在function 中,这意味着虽然它插件关闭时可能无法正确编译,尝试打开工作簿时不会出现错误。如果我确实设法弄清楚了一些事情(我现在已经没有时间了),我会告诉你的。

标签: vba excel


【解决方案1】:

我找了很多,但没有找到解决这个问题的好方法。

所以我在另一个文件中写了有问题的函数,如果我需要它,我可以这样激活它:

在模块中的 sp.mdb 上:

Public Function soap30object() As Object
Set soap30object = New SoapClient30
End Function

在主文件上:

Public Sub soap30object()
Dim ob As Object
Dim appAccess As New Access.Application
appAccess.OpenCurrentDatabase ("c:\sp\sp.mdb")
Set ob = appAccess.Run("soap30object")
End Sub

玩得开心!


另一种解决方案

在运行时替换Modul中的代码...

     Public Sub replacemodel(mdlname As String, fnd As String, cngto As String)
        Dim toi As Long, oldlin As String, i As Long, firstchr As String, linnewnum As Long, last_ As Boolean
        Dim frm As Form,mdl As Module 
        DoCmd.OpenForm mdlname, acDesign
        Set mdl = Forms(mdlname).Module
        toi = mdl.CountOfLines
        With mdl
            For i = 1 To toi
                linnewnum = i
                oldlin = .lines(i, 1)
                If InStr(oldlin, fnd) <> 0 Then
                    oldlin = Replace(oldlin, fnd, cngto)
                    .ReplaceLine i, oldlin
                    goto nexx
                End If
            Next i
        End With
nexx:
        DoCmd.Close acForm, mdlname, acSaveYes
        Set mdl = Nothing
        'All variables reset when you edit modul on 
        msgbox "Program will restart now..."
        DoCmd.Quit acQuitSaveAll
    end Sub

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2021-10-11
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多