(Excel 2010) I'm trying to grab specific lines from a variety of "target" workbooks in different but similar folders. I have found that I am able to pull this data when the source ("LM", the workbook the code is executing in, and that I want to pull the data to) and target workbooks are in the same folder without opening the target's workbook, but when they are in different locations (as they will be in practice) I receive a "Subscript out of range" error for the
LM.Worksheets("Sheet1").Range("B" & i + 1 & ":G" & i + 1).Value = _
Workbooks(filename).Worksheets("Sheet1").Range("B6:G6").Value
line. I have tried:
Using every variant & combination on pathname, dirname & filename, etc. as the argument for the latter Workbooks(). I have also had it MsgBox me the pieces and whole of pathname and filename to look at, which are error-free.
Replacing the latter Workbooks(filename) with a workbook variable (lets call it Targ), like LM (which works fine)
Changing the path with ChDir and ChDrive (& I have confirmed that the CurDir() is in fact the target directory when this is running) and doing the above
Using ThisWorkbook instead of LM for the call
Basically every permutation of the above ideas
Here is a stripped-down (because confidential stuff was in there) version of the code (which works fine if I un-comment Workbooks.Open and Workbooks.Close, but I want a more efficient method since this is a busy network and people are in-and-out of these files all the time. The fact that I can do this without opening the files if they're in the same folder tells me I'm onto something...)
Sub Import()
Dim directory As String, fileName As String, LM As Workbook, i as Integer
Set LM = Workbooks("LM.xlsm")
i = 1
Dim DirArray As Variant
'this is the array that handles the variations on the path, doesn't seem to be the problem
DirArray = LM.Worksheets("Sheet2").Range("DirTable")
Do While i <= UBound(DirArray)
directory = DirArray(i, 1)
dirname = "C:\blahblahblah"
fileName = Dir(dirname & "*.xl??")
pathname = dirname & fileName
ChDir dirname
' Workbooks.Open (dirname & fileName)
LM.Worksheets("Sheet1").Range("B" & i + 1 & ":G" & i + 1).Value = _
Workbooks(filename).Worksheets("Sheet1").Range("B6:G6").Value
i = i + 1
' Workbooks(fileName).Close
Loop
End Sub
If I could just figure out what is different when they're in the same folder! Navigating with ChDir and ChDrive doesn't seem to do any good...