来自文本文件的Excel-VBA导入模块(无需信任中心)

时间:2019-01-16 16:10:33

标签: excel vba module

我正在尝试创建一个自定义的子库和函数库,这些子库和函数另存为.txt文件,它们位于网络位置,正在创建的工作簿的各个用户可以根据他们选择的userform函数将其导入。工作簿的用户将仅通过用户表单使用工作簿。我不想要求他们修改其安全信任中心设置才能使此导入库代码正常工作,所以我不想使用wb.VBproject.References.import命令或将其添加为附件。

我发现这种方法很好用,但前提是没有其他工作簿打开。如果打开了另一个工作簿,则此代码最终会在另一个工作簿中插入一个新模块,因此userform调用是没有意义的。

我不知道这怎么可能,因为我在“ With ThisWorkbook”语句中引用了所有这些代码。我在做什么错了?

Sub importLib(libName As String)
  Application.DisplayAlerts = False

  Path = "C:\Users\(username)\Desktop\excelLibraries\" 'Example only, my path is actually a network location
  lib = Path & libName
  Dim wb As Workbook
  Set wb = ThisWorkbook
  With wb
    On Error Resume Next
    Dim wbModules As Modules

    Set wbModules = .Application.Modules 'wb=ThisWorkbook, but doesn't point to this workbook when other workbooks open???

    'wb.VBProject.VBComponents.Import lib '---> library saved as .bas, but this requires the user to change their security settings
    'wb.VBProject.References.AddFromFile lib '---> library saved as add-in reference, but this requires user to change security settings

'----This method works when no other workbooks are open
    For Each a In wbModules 'Clear any previous Library Module
        If a.Name = "Library" Then
            a.Delete
            Exit For
        End If
    Next

    Set m = wbModules.Add 'Create a new Library Module
    m.Name = "Library"
    m.InsertFile lib 'Insert the code
   On Error GoTo 0
 End With
 Application.DisplayAlerts = True

 End Sub

 Sub callsub()
  importLib "library1.txt"
 End Sub

1 个答案:

答案 0 :(得分:5)

进行以下更改似乎对我有用。

  1. Dim wbModules As Modules更改为Dim wbModules。否则会出现类型不匹配错误。
  2. 删除.Application中的Set wbModules = .Application.Modules

编辑:

正如@Mathieu Guindon在评论中指出的,但值得保留在问题正文中,Application指的是Excel应用实例 host Modules集合包含所有打开的模块,而与工作簿无关。

相关问题