excel:如果FileExists,如果文件中给定的值是x,则从给定的单元格中提取数据
我有一个函数,检查文件是否存在,如果文件存在,然后检查特定单元格中的特定值,如果是,则从给定的单元格拉取值。
问题是,当我运行这个代码时,一个拨号盒不断出现。 我插入了
Application.DisplayAlerts = False
到我的FileExists函数,但我仍然得到对话框,任何想法我做错了什么?
我的function:
Function FileExists(FilePath As String) As Boolean Application.DisplayAlerts = False 'Step 1: Declare your variables. Dim FileName As String 'Step 2: Use the Dir function to get the file name FileName = Dir(FilePath) 'Step 3: If file exists, return True else False If FileName <> "" Then FileExists = True _ Else: FileExists = False End Function Sub FileExits() End Sub
什么我插入公式框:
=IF(FileExists("path\filename.xls"),IF('path\[filename.xls]Sheet'!D$13="16m8", 'path\[filename.xls]Sheet'!D40, ""),"false")
从这里继续: https : //stackoverflow.com/questions/39452159/excel-pull-data-from-one-excel-file-to-another-if-the-file-exists
我在对OP的评论中有些误解。 是的,您可以通过这种方式(types)来检索值,但是您所看到的对话框是在文件不存在的情况下发生的,因为Excel的布尔逻辑不会短路。
这意味着如果指定的文件不存在,Excel仍然需要评估完整的expression式,并且如果指定的文件不存在, 则不能计算该部分。
IF('path\[filename.xls]Sheet'!D$13="16m8", 'path\[filename.xls]Sheet'!D40, "")
如上面提到的@pnuts,当Application.DisplayAlerts = False
,
[Excel]将采取默认选项,如果这些存在(例如没有保存为closures),但没有默认选项'我找不到你所告诉我使用的文件'
注意如果指定的文件确实存在,如果指定的图纸名称不存在,您仍然可以获得对话框。
替代scheme:
由于您已经在使用自定义函数FileExists
,只需使用如下所示(从Sid的答案稍微修改一下 )就可以从已closures的工作簿中获取值:
Function GetVal(path$, shtName$, cellRef$) Dim exists As Boolean, ret Dim fileName$, directory$, sht$, addr$ exists = Dir(Trim(path)) <> vbNullString If Not exists Then GoTo EarlyExit 'Else, if the file exists, get the values path = Replace(path, "/", "\") 'Get the query substrings: fileName = Dir(path) directory = Left$(path, Len(path) - Len(fileName)) 'Get the address of the cell, R1C1 style addr = Range(cellRef).Address(True, True, -4150) 'Build the query string in the ExecuteExcel4Macro function ret = ExecuteExcel4Macro("'" & directory & "[" & fileName & "]" & shtName & "'!" & addr) GetVal = ret EarlyExit: ret = "File or sheetname doesn't exist!" '## Modify as needed End Function
然后,修改你的逻辑,而不是:
=IF(FileExists("path\filename.xls"),IF('path\[filename.xls]Sheet'!D$13="16m8", 'path\[filename.xls]Sheet'!D40, ""),"false")
你做这个:
=IF(GetVal("path\filename.xls", "Sheet1", "D$13")="16m8", GetVal("path\filename.xls", "Sheet1", "D40"))
上面的函数使用与您的FileExists
相同的逻辑,并确保在将查询交给ExecuteExcel4Macro
内置函数之前存在该文件。