2014-02-19 48 views
-1

我有以下VBA函數打開一個Excel文件:VBA函數打開一個Excel

Function copie_sd() 

nom_fichier = Workbooks.Open(Filename:="C:\SD\copie_sd.xls") 
If nom_fichier = False Then 
    Range("A1").Select 
    copie_sd = "ERREUR" 
    Exit Function 
End If 

copie_sd = nom_fichier 

End Function 

,但我得到的錯誤:運行時錯誤「438」對象不支持此屬性或方法。

回答

0

如果你通過你的鱈魚e,你會看到Workbooks.Open()不會返回一個布爾變量,而是一個對Excel.Workbook對象的引用。

您的if語句應改爲測試Nothing而不是False

if nom_fichier Is Nothing Then 
    copie_sd = "ERREUR" 
    Exit Function 
End If 

另一件事: 你想 'ERREUR' 要打印到細胞A1
如果是的話,你應該叫

Range("A1").Value = "ERREUR" 
+0

一個UDF函數不能寫入到一個細胞。它不能有任何副作用。 – ja72

0

所有你需要的是

Function copie_sd(ByVal fn as String) as Boolean 
    copie_sd = False 
    Dim sd as Workbook  
    Set sd = Workbooks.Open(Filename:=fn) 
    If Not sd Is Nothing 
     copie_sd = True 
    End If  
End Function 

並以此

If copie_sd("C:\SD\copie_sd.xls") then 
    ' Other things to happen after open 
End If