Excel VBA获取真实文件夹路径长度(不包括Tilde)

时间:2015-07-02 22:00:33

标签: vba excel-vba excel

我的VBA代码每隔X次我的客户端保存文件就会创建一个备份文件(使用.SaveCopyAs)。最近一个客户端遇到了最大文件夹&文件路径长度似乎约为220个字符。我试图捕获长文件名,但Excel / Windows正在用〜(代字号)替换长文件夹名称,因此我无法获得真正的路径长度。

如何获取实际文件夹/文件路径字符串长度并阻止Windows使用"〜"?

Sub Backup()
    Set awb = ActiveWorkbook

    BackupFolder = awb.Path & "\Backups"   
    BackupFileName = BackupFolder & "\" & awb.Name
    BackupFileName = BackupFileName & " " & Format(Now(), "mmddhhmm") & ".xlsm"

    'debug.print BackupFileName 
    'Result: D:\MF\DOCUME~1\LATEST~1\MASTER~1\SUPERL~1\SUPERL~1\Backups\TestLength-07021655.xlsm

    'debug.print Len(BackupFileName)
    'Result: 83 but the TRUE length is well over 300 characters

    PathLen = Len(BackupFileName) 'Result: 83
    If PathLen > 215 Then 'This obviously doesn't fire
        BackupFolder = GetDesktop & "BidListBackups"
        BackupFileName = BackupFolder & "\" & awb.Name
        BackupFileName = BackupFileName & " " & sType & Format(Now(), "mmddhhmm") & ".xlsm"
    End If

    With awb
        .SaveCopyAs BackupFileName
    End With

    If PathLen > 215 
        MsgBox "Backup file was saved to your desktop", vbokonly
    End If   
End Sub

1 个答案:

答案 0 :(得分:0)

有关使用GetLongPathName API的代码,请参阅this answer。请注意,您需要从代码中显示的165增加缓冲区大小。