VBA - 从另一个工作簿调用

时间:2016-10-20 05:20:22

标签: excel vba excel-vba macros

尝试根据其他工作簿表中的数据删除工作表 - 通过比较和访问其他工作簿工作表中的数据,但它无法正常工作。如果工作表在同一工作簿中,我能够这样做,但是我不想每次都导入工作表。

代码到目前为止,我的问题是从另一个工作簿表调用。

sub delete()
     Dim wb As Workbook
     Dim wks As Worksheet
     Dim MyRange As Range
     Dim Cell As Range
     Set wb = Workbooks("name.xlsx")
     Set wks = wb.Worksheets("allnames")
     With wks
        Set MyRange = wks.Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
     End With
     On Error Resume Next
     Application.DisplayAlerts = False
     For Each Cell In MyRange
         Sheets(Cell.Value).Delete
     Next Cell
     Application.DisplayAlerts = True
     On Error GoTo 0
End Sub

提前致谢

1 个答案:

答案 0 :(得分:0)

也许你是在追求这样的事情:

Option Explicit

Sub delete()
     Dim toDeleteSheetsWb As Workbook
     Dim Cell As Range

     Set toDeleteSheetsWb = Workbooks("WorkbookWithSheetsToDelete.xlsx") '<-- set the workbook whose sheets will be deleted (change "WorkbookWithSheetsToDelete.xlsx" to its actual name)
     With Workbooks("name.xlsx").Worksheets("allnames") '<-- reference the worksheet from which to read worksheets names to be deleted in "WorkbookWithSheetsToDelete.xlsx" workbook
        Application.DisplayAlerts = False
        For Each Cell In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
            toDeleteSheetsWb.Sheets(Cell.Value).delete
        Next Cell
        Application.DisplayAlerts = True
     End With
End Sub