How to open consecutively-named lens files using a ZPL macro

Sometimes a macro needs to open a series of sequentially-named files, such as saved Monte Carlo files. This article demonstrates two different methods to loop through a series of files in a folder using a Zemax Programming Language (ZPL) macro. Method 1 is the more robust and recommended method, but both are presented for legacy purposes.

Authored By Nam-Hyong Kim, updated by Michael Humphreys


Article Attachments


Often, multiple OpticStudio files are generated with sequentially-labelled names as part of an analysis. One example is a Monte Carlo tolerance analysis, which produces files labelled "MC_T####" where "####" represents a number from 0001 to 9999. When these files are produced, it can be tedious to open and extract the necessary information from each one--especially if there are a large number of files. Luckily, OpticStudio provides users with a way to use a ZPL macro to open consecutively-named files and retrieve the requested values. In this article, we provide code for two macros. The first uses a FINDFILE keyword to locate and parse through the desired files, while the second uses a FOR loop. Each macro is provided via the Downloads section.

Method 1: FINDFILE

In the following code, the "filter$" variable on line 9 will only look for files beginning with MC_T and ending with .zmx, using the asterisk as a wildcard. In our case, this wildcard will represent the numbers '0001' through '9999', but this could be any valid character filename; it is not restricted to numeric values. The following macro will present a dialog box with the BROWSE keyword, prompting the user to select any valid .zmx file in the desired folder that contains the MC_T files. It will then open each file and extract the EFFL from the file using the OPEV and OCOD keywords, which use OpticStudio's compiled merit function operands to calculate the data, therefore running almost as fast as native code. The user should enter their custom code beginning on line 48.


Method 2: FOR loop

The included code snippet changes the value of the "myfiles_name$" string variable in the macro such that it contains the proper path and file name of the saved Monte Carlo file in each execution of the FOR loop. This macro is provided as an article attachment. Once downloaded, it should be placed in the "{Zemax}\Macros" directory. Then, it can be opened with any text editor or in OpticStudio via the Programming Tab...Edit/Run.


The macro is written so that the values of the "myfile_name$" is only printed instead of opening the files with those names. When incorporating this code into your own program, replace the PRINT keyword with the LOADLENS keywords to open the lens files instead. Upon execution of the included macro, you will get the following output window that shows the content of the string variable. 

text viewer



Was this article helpful?
0 out of 0 found this helpful



Please sign in to leave a comment.