【问题标题】:Getting an error when getting the path using macro使用宏获取路径时出错
【发布时间】:2017-12-13 21:34:26
【问题描述】:

在网上搜索将文件的当前路径放入 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

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

有什么想法吗?谢谢。

【问题讨论】:

  • ArrayoutofString 的代码在哪里?
  • 我已将该函数的代码添加到原帖中
  • 如果您调试,那么SepList() 中是否有内容? i 出错时的值是多少?
  • 经过进一步调查,似乎它只在文件加载期间产生错误。文件加载后,我可以毫无问题地使用上述功能。我想知道这是否与时间有关。

标签: vba path libreoffice-calc


【解决方案1】:

有更好的方法。

=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

有关问题的解释以及宏解决方案的工作原理,请参阅https://stackoverflow.com/a/39254907/5100564

编辑

以下表达式给出不带文件名的路径。要使其正常工作,必须在 Tools -> Options -> LibreOffice Calc -> Calculate 下的公式中启用正则表达式。

=MID(CELL("filename");2;SEARCH("/[^/]*$";CELL("filename"))-1)

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

【讨论】:

  • 我没有遇到过。但是,这给了我包括文件名在内的整个路径。我只想要包含目录的路径。
  • 完美运行!谢谢你这么彻底的回答。我不仅解决了这个问题,而且我现在明白为什么它不起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2017-01-13
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多