This will be my first question on this site, so bear with me.
So, I am trying to utilize the ExecuteExcel4Macro function, to reference a value in a different workbook, without having to open the workbook, as it will have to loop through a lot of workbooks in a directory, and reference the same cell on each workbook.
The problem arisen on this line:
wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"
which leads to the run-time error 1004 on this line:
month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1)))
If, let's say,
folderName = "C:\test\Accounts\O'Malley\Summary\"
, the error occurs.
Since folderName contains an apostrophe, ExecuteExcel4Macro is not recogninzing wbRef as what it is, a path to a folder, but closing that path too early in the path string, therefore resulting the error.
So my question is:
Is there a way to get around this apostrophe, without having to change the folder names, without having to open each individual workbook in the subfolder?
I've tried with double quotations, but didn't seem to do the trick.
Below is a draft of my code, or at least the context.
Sub refMonth()
Dim thisWb as Workbook, folderName as String, myDir as String, wbRef as String, thatSheet as String, month as String
Set thisWb = ActiveWorkbook
folderName = SelectFolder(thisWb)
If folderName = vbNullString Then GoTo Done
myDir = Dir(folderName & "*.xls")
thatSheet = "Sheet1"
wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"
Do Until myDir = vbNullString
month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1)))
'Do a lot of stuff, which works when in a folder without an apostrophe
myDir = Dir()
wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"
Loop
Done:
End Sub
Function SelectFolder(thisWb As Workbook)
Dim diaFolder As FileDialog, DirName As Variant
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.InitialFileName = strFolder(thisWb.Path)
If diaFolder.Show = True Then
'diaFolder.Show
DirName = diaFolder.SelectedItems(1)
If Right(DirName, 1) <> "\" Then
DirName = DirName & "\"
End If
Else
Set diaFolder = Nothing
Exit Function
End If
Set diaFolder = Nothing
SelectFolder = DirName
End Function
Function strFolder(ByVal strFolder0) As String
strFolder = Left(strFolder0, InStrRev(strFolder0, "\") - 1) & "\"
End Function
Any help is appreciated, even if it's just to tell me it's impossible to get around the apostrophe.
I couldn't find an answer on here, but if there is one, please point me in the right direction.
You need to double the apostrophe to escape it:
wbRef = "'" & Replace$(folderName & "[" & myDir & "]" & thatSheet, "'", "''") & "'!"