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

MacOS中使用VBA获取MP4视频时长触发错误5的求助

解决MacOS VBA获取MP4时长的Error 5问题

你的代码存在几个关键问题,逐一修正即可解决错误:

1. 修复函数返回名不匹配问题

函数定义为GetMP4Length,但最后返回语句用了GetMP4FileLength,这会导致逻辑错误,直接修正为:

GetMP4Length = durationInSeconds

2. 修正MacScript的字符串拼接逻辑

原代码硬编码路径且嵌套引号处理有误,正确做法是动态传入filePath参数,并正确转义路径中的特殊字符:

  • 先处理路径中的单引号:shell环境中单引号需要转义为'\''
  • 重新构造shell命令,确保引号嵌套正确

修正后的MacScript调用:

' 处理路径中的单引号,避免shell解析失败
Dim escapedPath As String
escapedPath = Replace(filePath, "'", "'\''")
' 构造正确的shell命令
durationOutput = MacScript("do shell script ""mdls -name kMDItemDurationSeconds '" & escapedPath & "'""")

3. 增加异常处理逻辑

如果文件不存在或mdls无法获取时长,Split操作会报错,需要添加错误捕获:

On Error Resume Next
durationInSeconds = Val(Split(durationOutput, "=")(1))
If Err.Number <> 0 Then
    GetMP4Length = -1 ' 返回-1标记获取失败
    Exit Function
End If
On Error GoTo 0

完整修正后的函数

Function GetMP4Length(filePath As String) As Double
    Dim durationOutput As String
    Dim durationInSeconds As Double
    Dim escapedPath As String
    
    ' 初始化返回值为-1(表示获取失败)
    GetMP4Length = -1
    
    ' 转义路径中的单引号
    escapedPath = Replace(filePath, "'", "'\''")
    
    ' 执行shell命令,捕获执行错误
    On Error Resume Next
    durationOutput = MacScript("do shell script ""mdls -name kMDItemDurationSeconds '" & escapedPath & "'""")
    If Err.Number <> 0 Then
        Exit Function
    End If
    On Error GoTo 0
    
    ' 解析时长结果,捕获解析错误
    On Error Resume Next
    durationInSeconds = Val(Split(durationOutput, "=")(1))
    If Err.Number = 0 Then
        GetMP4Length = durationInSeconds
    End If
End Function

额外注意事项

  • 确保传入的是绝对路径,相对路径可能导致mdls无法定位文件
  • 在Office for Mac中运行时,需确保应用有访问目标文件目录的权限(可在系统偏好设置→安全性与隐私中授权)
  • 测试时直接传入实际路径参数,例如:Debug.Print GetMP4Length("/Users/simonsanchez/Downloads/My Folder/my file.mp4")

内容的提问来源于stack exchange,提问作者Simón Sánchez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:54:58