I am using the below code to copy specific sheets to a new workbook and then break the external links in the new workbook. The code works perfectly fine. However, when i save it as 'Add-In' and run it in some other excel file I get the error "Run-time error '13': Type mismatch" at line "For Each link In wbTarget.LinkSources(xlLinkTypeExcelLinks)". Can someone help me get the below code working as an Add-In please?
VBA Code:
Sub CopySheets()
Dim wbSource As Workbook
Dim wbTarget As Workbook
Dim ws As Worksheet
Dim sheetNames As Variant
Dim targetSheet As Worksheet
Dim link As Variant
' Disable screen updating
Application.ScreenUpdating = False
' Set the source workbook
Set wbSource = ThisWorkbook
' Define the sheet names to be copied
sheetNames = Array("SheetNameA", "SheetNameB", "SheetNameC", "SheetNameD", "SheetNameE")
' Create a new workbook
Set wbTarget = Workbooks.Add
' Loop through each sheet name
For Each ws In wbSource.Sheets
If IsInArray(ws.Name, sheetNames) Then
' Copy the sheet to the new workbook
ws.Copy After:=wbTarget.Sheets(wbTarget.Sheets.Count)
Set targetSheet = wbTarget.Sheets(wbTarget.Sheets.Count)
targetSheet.Name = ws.Name
End If
Next ws
' Break links in the new workbook
For Each link In wbTarget.LinkSources(xlLinkTypeExcelLinks)
wbTarget.BreakLink link, xlLinkTypeExcelLinks
Next link
' Delete the default "Sheet1" in the new workbook
Application.DisplayAlerts = False ' Disable alerts
On Error Resume Next
wbTarget.Sheets("Sheet1").Delete
On Error GoTo 0
Application.DisplayAlerts = True ' Enable alerts
' Reactivate the source workbook
wbSource.Activate
' Enable screen updating
Application.ScreenUpdating = True
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function