预先感谢您的任何帮助。我的知识是初级水平。我可以阅读代码,但很难写作。
此外,我认为总是有更好(更有效)的方法来编写代码。
解决方案是几个目标的组合: 1.带指定宏的命令按钮(已完成) 2.错误处理(有一点代码) 3.确定要从中转移的第二个工作簿(包含此代码) 4.将90+命名范围的值复制并粘贴到工作簿A(使用宏录制器的穴居人代码) 5.将5个名称范围的对象(图片)复制并粘贴到工作簿A中(尚未到目前为止) 6.用户反馈(传输成功或传输失败,显示错误消息)
代码:(跳过目标1)
Sub Button_Transfer_FromOlderVersion()
' Start of Error Handling
On Error GoTo Errorcatch
' Declare string variable and use current open workbook filename as value
Dim WorkbookNameNew As String
WorkbookNameNew = ThisWorkbook.Name
' Declare string variable for 2nd workbook not yet identified
Dim WorkbookNameOld As String
' Find out the name of the 2nd workbook
' Declare string variable for finding and separating the filename from the path
Dim sFileName As String
' Show the open dialog and pass the selected file name to the string variable "sFileName"
sFileName = Application.GetOpenFilename
' If the user cancels finding the workbook file then exit subroutine
If sFileName = "False" Then Exit Sub
' Troubleshooting: Show me the filename with path of Workbook B
MsgBox sFileName
' Troubleshooting: Show me the filename of Workbook A
MsgBox WorkbookNameNew
' Open Workbook B which the user just selected
Workbooks.Open Filename:=sFileName
' Separate the filename from the path for Workbook B
WorkbookNameOld = Dir(sFileName)
' Troubleshooting: Show me the filename of Workbook B
MsgBox WorkbookNameOld
' Make sure Workbook B is the active workbook
Windows(WorkbookNameOld).Activate
' Make sure the correct worksheet is active
Worksheets("WorksheetName").Activate
' Select and copy the value of the first Named Range
Range("NamedRange01").Select
Selection.Copy
' Make Workbook A the active workbook
Windows(WorkbookNameNew).Activate
' Select the corresponding Named Range in Workbook A
Range("NamedRange01").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
' User Feedback of successful transfer and name of Workbook B
MsgBox ("TRANSFER COMPLETED FROM:" & " " & WorkbookNameOld)
Exit Sub
' Finish Error Handling
Errorcatch:
MsgBox Err.Description
End Sub
如果间距,缩进和评论未针对阅读进行优化,我深表歉意。我还在学习最佳实践。
请注意:某些名称范围拼写不同,我需要映射它们,以便复制/粘贴准确。
此外,不是使用复制/粘贴不是更好的列出具有关联变量的数组中的所有命名范围?将所有值和对象复制到数组中然后切换到工作簿A并粘贴所有内容不是更好吗?
再次感谢你的帮助。
在复制或粘贴之前,您无需费心激活工作簿或工作表。这只会减慢速度。此外,您可以更改屏幕更新和计算,以加快速度。
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Windows(WorkbookNameOld).Worksheets("WorksheetName").Range("NamedRange01").Copy
Windows(WorkbookNameNew).ActiveSheet.Range("NamedRange01").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic