vba函数打开excel
我使用以下VBA函数打开excel文件:vba函数打开excel,vba,excel,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 但是我得到一个错
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”对象不支持此属性或方法。我相信您可能希望
像这样对变量进行暗显
Dim nom_fichier as workbook
然后使用set
进行设置
set nom_fichier = workbooks.open
另外,下面的行不适用于对象变量
if nom_fichier = false then
这可能会有帮助
如果您单步执行代码,您将看到工作簿.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"
你所需要的只是
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
UDF函数无法写入单元格。它不能有任何副作用。