VBA - Calling from another workbook

爷,独闯天下 提交于 2020-07-20 04:07:24

问题


Trying to delete sheets based on data from another workbook sheet - By comparing and accessing data from another workbook sheet, however its not working. I was able to do it if the sheet was in the same workbook, however i do not want to import the worksheet every time.

Code so far, My problem is calling from another workbook sheet.

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

Thanks in advance


回答1:


maybe you're after something like this:

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


来源:https://stackoverflow.com/questions/40146021/vba-calling-from-another-workbook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!