宏的VBA Open Workbook失败“(找不到路径和文件名)。检查拼写......”

时间:2011-09-28 20:24:32

标签: excel vba

我有以下代码,它应该只是从主工作簿中打开一个工作簿,以允许我粘贴一些我稍后将从数据库中检索的信息。我每次尝试打开工作簿时都会收到标题中的错误。我之前使用过类似的代码,没有任何问题。这些文件保存在远离桌面的服务器上,但每次都是正确的路径。我一遍又一遍地检查过。可能是罪魁祸首?

Sub copyDealerDataToWorkbook(ByVal targetID As Integer)

    Dim mainWB      As Workbook    
    Dim directory   As String
    Dim fn          As String
    Dim aFile       As Excel.Application

    Set aFile = CreateObject("Excel.Application")

    Set mainWB = ActiveWorkbook
    directory = ActiveWorkbook.Path

    'append a "\"
    If InStrRev(directory, "\") < Len(directory) Then
        directory = directory & "\"
    End If

    fn = targetID & ".xls"

    aFile.Application.Visible = True
    aFile.Workbooks.Open directory & fn 'ERROR ON THIS LINE
    aFile.Parent.Windows(1).Visible = True
End Sub

我也试过以下代码......

Sub copyDealerDataToWorkbook(ByVal targetID As Integer)
    Dim foreignWB   As Workbook
    Dim mainWB      As Workbook
    Dim directory   As String
    Dim fn          As String

    Set mainWB = ActiveWorkbook
    directory = ActiveWorkbook.Path

    'append a "\"
    If InStrRev(directory, "\") < Len(directory) Then
        directory = directory & "\"
    End If

    fn = targetID & ".xls"

    Set foreignWB = Workbooks.Open(fileName:=directory & fn) 'ERROR ON THIS LINE
End Sub

3 个答案:

答案 0 :(得分:0)

首先使用带有文件名的硬编码,然后测试是否打开。

样本

Workbooks.open "\\Oesdfiles\Users\FName LName\Reports\test_data\monthly EDS reports\Number by dealer Per importer\test_2011\2011-01January\YourFileHere.xls"

如果是,则您的目录或fn var是错误的。

如果否,请尝试在办公室按钮/ Excel选项/资源/诊断中使用办公室诊断

再试一次。

如果不能正常工作,那么您的excel需要重新安装。

[]的

答案 1 :(得分:0)

If Dir(directory & fn) <> "" Then
    'do the magic
Else
    MsgBox "Directory and file not found:" & vbCrLf & directory & fn, vbCritical, "Invalid Directory"
End If

答案 2 :(得分:0)

targetID As Integer

仅当您的Excel工作簿具有不带前导零的数字文件名时才有效。此外,在这种情况下,没有必要将targetID设为Integer,因为您没有迭代或对值进行计算,我会改为:

targetID As String

编辑:我刚刚意识到这是2年前发布的。 :P