使用宏导出模块

时间:2017-09-11 21:06:18

标签: module export

我正在逐步使用this帖子导出模块,但没有任何反应。是否有安全设置允许VBA权限导出模块?

我正在将工作簿中的几个选项卡复制到新工作簿中,但选项卡中包含导致链接断开的宏。为了解决这个问题,我想移动模块并重新关联宏。如果我无法使用它,我将复制整个工作簿并删除目标中不需要的信息。

以下是上述帖子中的代码:

Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)

' Description:  copies a module from one workbook to another
' example: CopyModule Workbooks(ThisWorkbook), "Module2",
'          Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
' Notes:   If Module to be copied already exists, it is removed first,
'          and afterwards copied

Dim strFolder                       As String
Dim strTempFile                     As String
Dim FName                           As String

If Trim(strModuleName) = vbNullString Then
    Exit Sub
End If

If TargetWB Is Nothing Then
    MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
    Exit Sub
End If

strFolder = SourceWB.Path
If Len(strFolder) = 0 Then strFolder = CurDir

' create temp file and copy "Module2" into it
strFolder = strFolder & "\"
strTempFile = strFolder & "~tmpexport.bas"

On Error Resume Next
FName = Environ("Temp") & "\" & strModuleName & ".bas"
If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
    Err.Clear
    Kill FName
    If Err.Number <> 0 Then
        MsgBox "Error copying module " & strModuleName & "  from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
        Exit Sub
    End If
End If

' remove "Module2" if already exits in destination workbook
With TargetWB.VBProject.VBComponents
    .Remove .Item(strModuleName)
End With

' copy "Module2" from temp file to destination workbook
SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
TargetWB.VBProject.VBComponents.Import strTempFile

Kill strTempFile
On Error GoTo 0

End Sub

0 个答案:

没有答案