VBA从添加到工作簿导入udf模块

时间:2016-02-27 12:10:20

标签: excel vba excel-vba excel-addins

所以,我有一个带有几个UDF的.xlam AddIn。作为一个众所周知的absolute path problem的解决方法,我将我的UDF导入到当前的工作簿,因此可以从工作簿调用UDF,而不是使用以下代码从AddIn调用:

Sub CopyOneModule()
Dim FName As String
On Error GoTo errhandler
With ThisWorkbook
    FName = .Path & "\code.txt"
    .VBProject.VBComponents("HMFunctions").Export FName
End With
ActiveWorkbook.VBProject.VBComponents.Import FName
MsgBox ("Functions successfully imported")
errhandler:
If Err.Number <> 0 Then
        Select Case Err.Number
        Case Is = 0:
        Case Is = 1004:
            MsgBox "Please allow access to Object Model and try again.", vbCritical, "No Access granted"
        End Select
End If

似乎工作正常。所以,我的(可能是愚蠢的)问题是:有没有办法让导入的UDF工作簿“unsee”存储在AddIn中的相同模块?需要避免以下可能非常混乱的情况: 2 functions instead of 1

提前谢谢你。

1 个答案:

答案 0 :(得分:0)

正如snoopen所建议的那样,从临时文本文件中删除私有标签就像一个魅力。问题已结束。这是我用于导入的最终代码:

    Sub CopyOneModule()
Dim FName As String
Dim FileContent As String
Dim TextFile As Integer
Dim ws As Workbook

Set ws = ActiveWorkbook

On Error GoTo errhandler
With ThisWorkbook
    FName = .Path & "\code.txt"
    .VBProject.VBComponents("HMFunctions").Export FName
End With

TextFile = FreeFile
Open FName For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
Close TextFile
FileContent = Replace(FileContent, "Private", "")
TextFile = FreeFile
Open FName For Output As TextFile
Print #TextFile, FileContent
Close TextFile

ws.VBProject.VBComponents.Import FName
MsgBox ("Functions successfully imported")
errhandler:
If Err.Number <> 0 Then
        Select Case Err.Number
        Case Is = 0:
        Case Is = 1004:
            MsgBox "Please allow access to Object Model and try again.", vbCritical, "No Access granted"
        End Select
    End If

End Sub