gpt4 book ai didi

VBA 将模块从一个 Excel 工作簿复制到另一工作簿

转载 作者:行者123 更新时间:2023-12-02 07:16:44 25 4
gpt4 key购买 nike

我正在尝试使用 VBA 将模块从一个 Excel 工作簿复制到另一个 Excel 工作簿。

我的代码:

'Copy Macros

Dim comp As Object
Set comp = ThisWorkbook.VBProject.VBComponents("Module2")
Set Target = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm").VBProject.VBComponents.Add(1)

由于某种原因,这复制了模块,但没有复制里面的VBA代码,为什么?

请有人告诉我哪里出了问题吗?

谢谢

最佳答案

下面的

Sub CopyModule,接收3个参数:

1.源工作簿(作为Workbook)。

2.要复制的模块名称(作为字符串)。

3.目标工作簿(如工作簿)。

复制模块代码

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
<小时/>

代码(用于使用帖子数据运行此代码):

Option Explicit

Public Sub Main()

Dim WB1 As Workbook
Dim WB2 As Workbook

Set WB1 = ThisWorkbook
Set WB2 = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")

Call CopyModule(WB1, "Module2", WB2)

End Sub

关于VBA 将模块从一个 Excel 工作簿复制到另一工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40956465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com