This article demontrates how to process/read individual files and directories in Unix file system using Basic and LibreOffice Calc Macro and put the file names/directory names in LibreOffice Calc cells.
For LibreOffice automation, it is necessary to know file system and directory processings. This tutorial is based on Unix file system which is different than Windoze.
In this article, the macro would read the contents of an entire directory and find out the files and directories and list them in Calc cells. Say, the file system structure is like this in a typical Ubuntu system in the path /usr/include
There are lots of Directories and Files. We would like to list down entire contents inside Calc cells.
Basic provides function “Dir” which can be used to read the contents of a Directory.
Dir (path, attributes) As String
First argument of the Dir function is the path string to be read. Second argument tells Dir function which type of elements in that path to be returned. Pass on “0” for file and “16” for Directories for second argument. Both the arguments are optional.
Once the first Dir call is successful, call the function again without argument inside a loop to get the same items from the function resulting listing of entire Directory contents.
To run, create a new Calc file and Copy and paste this entire code block below in Macro Editor in LibreOffice and run.
Sub list_files() Dim i, strFile path ="/usr/include/" strFile = Dir(path,0) i = 1 while strFile <> "" my_cell = ThisComponent.Sheets(0).getCellbyPosition(1,i) my_cell.String = strFile strFile = Dir ' returns next entry i = i + 1 wend End Sub Sub list_directory() Dim i, strDir path ="/usr/include/" strDir = Dir(path, 16) i = 1 while strDir <> "" my_cell = ThisComponent.Sheets(0).getCellbyPosition(2,i) my_cell.String = strDir strDir = Dir ' returns next entry i = i + 1 wend End Sub
After run, the contents of /usr/include would be shown in Calc. First column would contain the Files and second column would contain the Directories.
Function References – Used in this article
Dir (path, attributes)
Return Value: String
List of attribute types:
|16||Directory or folder|
|64||File name is an alias|
Looking for Something Else?
If you are looking for something else in LibreOffice macro tutorials, Or, wants to learn more about it, please follow below link for complete Macro Tutorials Index: