使用宏获取路径时出错

Getting an error when getting the path using macro

在网上搜索将文件的当前路径放入 LibreOffice Calc 单元格的解决方案后,我遇到了以下宏代码:

function GetPath() as string
  GlobalScope.BasicLibraries.loadLibrary("Tools")
  GetPath = Tools.Strings.DirectoryNameoutofPath(ThisComponent.url, "/")
end function

这一直有效,直到我关闭文件,然后重新打开它。当我重新打开它时,我收到以下错误消息:

Inadmissible value or data type.
Index out of defined range.

此错误是在工具宏库中以下函数的最后一行生成的。

Function FileNameoutofPath(ByVal Path as String, Optional Separator as String) as String
Dim i as Integer
Dim SepList() as String
    If IsMissing(Separator) Then
        Path = ConvertFromUrl(Path)
        Separator = GetPathSeparator()      
    End If
    SepList() = ArrayoutofString(Path, Separator,i)
    FileNameoutofPath = SepList(i)
End Function

该函数的代码是...

Function ArrayOutOfString(BigString, Separator as String, Optional MaxIndex as Integer)
    Dim LocList() as String
    LocList=Split(BigString,Separator)

    If not isMissing(MaxIndex) then maxIndex=ubound(LocList())  

    ArrayOutOfString=LocList
End Function

我不确定为什么这会在文件加载时产生错误,但此后继续工作。

有什么想法吗?谢谢

有更好的方法。

=LEFT(CELL("filename");FIND("#$";CELL("filename"))-1)

来源:https://ask.libreoffice.org/en/question/67271/how-to-automatically-display-file-path-in-a-cell/ CELL 函数的文档:https://help.libreoffice.org/Calc/Information_Functions#CELL

或者,要使用宏执行此操作,请将以下 WritePath 子例程分配给 View created 事件中的 运行。

function GetPath() as string
    On Error Goto ErrorHandler
    GlobalScope.BasicLibraries.loadLibrary("Tools")
    GetPath = Tools.Strings.DirectoryNameoutofPath(ThisComponent.url, "/")
    ErrorHandler:
end function

Sub WritePath
    oSheet = ThisComponent.getSheets().getByIndex(0)
    oCell = oSheet.getCellRangeByName("A1")
    oCell.setString(GetPath())
End Sub

有关问题的解释以及宏解决方案的工作原理,请参阅

编辑:

下面的表达式给出了没有文件名的路径。要使其正常工作,必须在 工具 -> 选项 -> LibreOffice Calc -> 计算.

下的公式中启用正则表达式
=MID(CELL("filename");2;SEARCH("/[^/]*$";CELL("filename"))-1)

https://wiki.openoffice.org/wiki/Documentation/How_Tos/Regular_Expressions_in_Writer