问题
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