I am trying to copy a sheet from one workbook to another. The below code worked perfectly well when the name of the workbook and worksheet was hard-coded.
Instead when i tried to reference the sheet-name to be copied from a text in a cell, i am getting
Run-time error '9': Subscript out of range.
The error occurs in the Bold line. I tried the text with and without quotes (single and double both).
Sub copy_dss_data_1()
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Dim shttocopy As Worksheet
Dim wbname As String
' check if the file is open (source file)
ret = Isworkbookopen(ThisWorkbook.Path & "\" & Range("J2"))
If ret = False Then
' open file
Set wkbSource = Workbooks.Open(ThisWorkbook.Path & "\" & Range("J2"))
Else
Set wkbSource = Workbooks(Strings.Trim(Range("J2")))
End If
' check if the file is open
ret = Isworkbookopen(ThisWorkbook.Path & "\Book1.xlsm")
If ret = False Then
' open file
Set wkbDest = Workbooks.Open(ThisWorkbook.Path & "\Book1.xlsm")
Else
Set wkbDest = Workbooks("Book1.xlsm")
End If
***Set shttocopy = wkbSource.Sheets(Strings.Trim(Range("J3")))
shttocopy.Copy wkbDest.Sheets(1)***
End Sub
Function Isworkbookopen(filename As String)
Dim ff As Long, ErrNo As Long
Dim wkb As Workbook
Dim nam As String
wbname = filename
On Error Resume Next
ff = FreeFile()
Open filename For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: Isworkbookopen = False
Case 70: Isworkbookopen = True
Case Else: Error ErrNo
End Select
End Function