VBA从外部工作表导入数据 – variables工作表名称
我期待着做到以下几点:
- 目标Worksheet中的CommandButton打开一个源文件(对话框来select哪一个)
- 在源文件中查找工作表(始终使用相同的名称 – “性能”)
- 复制一系列单元格(实际上是一些单独的范围 – 将被添加)
- 确保目标工作表(与源工作表中的单元格I2具有相同的名称)存在
- 将值粘贴到目标Worksheet中的相同范围
- closures源文件
我到目前为止:
Private Sub CommandButton1_Click() Dim SourceFile As String Dim SourceBook As Workbook Dim DestinationBook As Workbook Dim desiredName As String Set DestinationBook = ThisWorkbook SourceFile = Application.GetOpenFilename(fileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm") Set SourceBook = Workbooks.Open(SourceFile) SourceBook.Sheets("Performance").Activate desiredName = ActiveSheet.Range("I2") Application.CutCopyMode = True SourceBook.ActiveSheet.Range("E25:I64").Copy DestinationBook.Activate If WorksheetExists = False Then MsgBox "Couldn't find " & desiredName & " sheet within destination workbook" Call SourceBook.Close(False) Exit Sub Else Range("E25:I64").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False Call SourceBook.Close(False) End If End Sub Function WorksheetExists() As Boolean Dim sh As Object For Each sh In DestinationBook.Worksheets If sh.Name = desiredName Then WorksheetExists = True: sh.Activate Exit For Next End Function
我得到运行时错误'424':Object Required
有什么build议么…?
提前致谢!
这里是你最新的代码的修改。 注意这些增加:1)“Option Explicit”确保你已经正确地声明了所有variables,2)variables已经被分配给重要的工作簿,工作表和范围,3)需要的variables被传递给WorkSheetExists
函数。 为此,在DestinationBook
应该有名为“Performance”和“testSheet”的工作表,以及SourceBook
I2
中的“testSheet”。 请记住,这只是一个“让你走”的尝试,所以我希望你需要修改。
Option Explicit Sub test() Dim SourceFile As String Dim SourceBook As Workbook, performanceSh As Worksheet Dim DestinationBook As Workbook Dim desiredName As String Set DestinationBook = ThisWorkbook SourceFile = Application.GetOpenFilename(fileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm") Set SourceBook = Workbooks.Open(SourceFile) Set performanceSh = SourceBook.Sheets("Performance") desiredName = performanceSh.Range("I2") Application.CutCopyMode = True performanceSh.Range("E25:I64").Copy If WorksheetExists(DestinationBook, desiredName) = False Then MsgBox "Couldn't find " & desiredName & " sheet within destination workbook" SourceBook.Close(False) Exit Sub Else Range("E25:I64").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False Application.CutCopyMode = False SourceBook.Close(False) End If End Sub Function WorksheetExists(destWk As Workbook, theName As String) As Boolean Dim sh As Object For Each sh In destWk.Worksheets If sh.Name = theName Then WorksheetExists = True: sh.Activate Exit For Next End Function