You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA路径检测函数未正确识别存在的文件夹问题求助

Excel VBA路径检测函数未正确识别存在的文件夹问题求助

大家好,我最近碰到一个搞了好几个小时都没解决的VBA问题,想请各位帮忙排查一下!

我写了一个用来检测路径是否存在的函数,然后在代码里调用它来选择要使用的路径。逻辑很简单:先检查filePath1,存在就用它;不存在就检查filePath2,存在就用它;如果都不存在,就用当前工作簿的路径。

但奇怪的是,明明filePath2指向的文件夹是确实存在的,代码却总是走到第三个分支,输出“Found in C”,完全跳过了第二个判断分支,实在搞不懂哪里出问题了!

先贴我的检测函数代码:

Function GetFilePathIfExists(filePath As String) As String
    If Len(Dir(filePath)) > 0 Then
        GetFilePathIfExists = filePath
    Else
        GetFilePathIfExists = ""
    End If
End Function

再贴调用这段函数的代码部分:

Dim filePath1 As String
Dim filePath2 As String
Dim pathToCheck As String
Dim pathToTake As String

' 指定文件路径
filePath1 = "firstPath\invalid"
filePath2 = "C:\Users\myusername\Desktop\TestFolder"

If GetFilePathIfExists(filePath1) <> "" Then
    Debug.Print "Found in A"
    pathToTake = filePath1
ElseIf GetFilePathIfExists(filePath2) <> "" Then
    Debug.Print "Found in B"
    pathToTake = filePath2
Else
    ' 如果两个路径都没找到,使用当前工作簿的路径
    pathToTake = ThisWorkbook.Path
    Debug.Print "Found in C"
End If

我反复确认过C:\Users\myusername\Desktop\TestFolder这个文件夹是真实存在的,而且试过把程序里其他能正常工作的路径放到这个检测函数里,结果也一样识别不出来,实在摸不着头脑了,有没有人能帮我找出错误点啊?

备注:内容来源于stack exchange,提问作者yesIamFaded

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 10:23:09