Workbook.open中的Vba股票[如果我按F5继续]

时间:2013-05-27 16:40:11

标签: excel vba

当我尝试从我的宏打开excel文件时:我遇到 1004 问题,如果我调试代码并按 F5 继续,则会打开该文件没有任何问题,如果我逐行调试代码工作。

Sub openFile2(ruta, fich, destino As Worksheet)

    Application.CutCopyMode = False

    Dim aux As String
    aux = ruta & "\" & fich
    ChDir ruta
    Workbooks.Open Filename:=fich       

End Sub

我的价值观

芸香

  

“C:\ Users \ Usuario \ Desktop \ Swap \ @&& Informes&& @ \ Informes 2G \ Input”

fich

  

“CNA_GsmRel_Z2_23052013.xls”

我也尝试过:

    aux = ruta & "\" & fich
    Workbooks.Open Filename:=aux

1 个答案:

答案 0 :(得分:1)

Workbooks.Open需要完整的路径Filename,因此它应该是Workbooks.Open(FileName:=aux)而不是Workbooks.Open(FileName:=fich)

声明工作簿变量wkb可让您控制工作簿以进行进一步操作。

在运行代码之前保存包含代码的工作簿。

使用下面更健壮的代码。

Sub sample()
    ruta = "C:\Users\Usuario\Desktop\Swap\@&&Informes&&@\Informes 2G\Input"
    fich = "CNA_GsmRel_Z2_23052013.xls"
    openFile2 ruta, fich, ThisWorkbook.Sheets(1)

End Sub

Sub openFile2(ruta, fich, destino As Worksheet)

    Dim aux As String
    aux = ruta & "\" & fich

    Dim wkb As Workbook

    If IsWorkBookOpen(aux) Then
        Set wkb = Workbooks(fich)
    Else
        Set wkb = Workbooks.Open(FileName:=aux)
    End If

End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    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