ExecuteExcel4Macro,包含撇号的路径

时间:2015-12-08 12:40:32

标签: excel vba excel-vba

这是我在这个网站上的第一个问题,请耐心等待。

所以,我正在尝试利用ExecuteExcel4Macro函数来引用不同工作簿中的值,而不必打开工作簿,因为它必须遍历目录中的许多工作簿,并引用相同的单元格在每个工作簿上。

这一问题出现了:

wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"

导致此行上的运行时错误1004:

month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1)))

如果,让我们说,

folderName = "C:\test\Accounts\O'Malley\Summary\"

,发生错误。

由于folderName包含撇号,因此ExecuteExcel4Macro无法识别wbRef,它是文件夹的路径,但在路径字符串中过早关闭该路径,从而导致错误。

所以我的问题是:

有没有办法摆脱这个撇号,而无需更改文件夹名称,而无需在子文件夹中打开每个单独的工作簿?

我尝试过双引号,但似乎没有做到这一点。

下面是我的代码草稿,或者至少是上下文。

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

任何帮助都会受到赞赏,即使只是告诉我它无法绕过撇号。

我在这里找不到答案,但如果有答案,请指出正确的方向。

1 个答案:

答案 0 :(得分:2)

你需要加倍撇号才能逃脱它:

wbRef = "'" & Replace$(folderName & "[" & myDir & "]" & thatSheet, "'", "''") & "'!"