我想编写一个宏,您可以浏览一个excel文件。然后在浏览的文件中,按工作表名称搜索工作表(3.方差分析),然后将数据从该工作表复制到实际的excel工作表(也称为3.方差分析)。
我已经获得以下代码:
Sub YOY()
Dim strFileToOpen As String
Dim Wbk_WeeklyTemplate As Workbook
Dim Tgt_ShtNm As String
Dim Src_ShtNm As String
'Choosing an Excel File using File dialog Box and capturing the file path in the variable
strFileToOpen = Application.GetOpenFilename(Title:="Please select the file to open", FileFilter:="Excel Files *.xls* (*.xls*),")
'Checking if file is selected
If strFileToOpen = "False" Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Set Wbk_WeeklyTemplate = Workbooks.Open(strFileToOpen)
End If
''Refer sheet by Sheet CodeName
Src_ShtNm = SheetName(Wbk_WeeklyTemplate, "3. Variance analysis")
Tgt_ShtNm = SheetName(ThisWorkbook, "3. Variance analysis")
Wbk_WeeklyTemplate.Sheets(Src_ShtNm).Range("D9:E16").Copy
ThisWorkbook.Sheets(Tgt_ShtNm).Range("M9:N16").PasteSpecial xlPasteValues
End Sub
''The function SheetName returns the actual name of the sheet by passing sheet code name
Function SheetName(Wb As Workbook, CodeName As String) As String
SheetName = Wb.VBProject.VBComponents(CodeName).Properties("3. Variance analysis").Value
End Function
现在我可以打开文件,但是在复制和粘贴过程中它停止了。它说Function()部分出错。