Spreadsheet Problem Solving for ChE Faculty
Calling Fortran routines from Excel1
Fortran routines (also C/C++ routines) can be called from a VBA2 module in Excel. A couple rules have to be followed to make this work: The Fortran code has to be compiled as a DLL3 file not an EXE4 file, and appropriate DLL attributes declaration statements must be included in the code. Popular compilers, such as Compaq Digital Visual Fortran 6.5, have this capability. In the VBA code, Declare statements must be included that identify the Fortran routine name with the DLL file and define the arguments used. One of the advantages of using an external programming language, like Fortran, is that large libraries of numerical methods routines are made available. Here is an example that makes use of the IMSL routines in Visual Fortran 6.5: The spreadsheet shown below (available as [Link]) solves the von Karman equation for the Fanning friction factor, f, as a function of a given Reynolds number, Re. The equation being solved is shown on the worksheet as a Mathtype object.
The formula in cell B6 is:
=Getf(fstart,Re)
1 2
These notes are adapted from two short articles by Edward M. Rosen. VBA = Visual Basic for Applications, the programming language in Excel 3 DLL = dynamic link library 4 EXE = stand-alone, executable
Calling Fortran Routines from Excel
The user-defined function, Getf, can be seen via the Visual Basic Editor, and its VBA code is
The Getf function calls the Fortran 90 subroutine Fanning (available as Fanning.f90), passing through the two input arguments, f0 and Re. The Fortran subroutine returns one output argument, f. That returned argument is set equal to Getf so that it appears in the cell on the worksheet. Note that each Fortran routine, like Fanning here, must have its own Declare statement, and that statement must define each argument separately. Also, the VBA function must be of the Public type. The Fortran code for the Fanning subroutine is
-2-
Calling Fortran Routines from Excel
Note the !DEC$ compiler directives. These are required. The Fanning subroutine calls the IMSL routine Zreal to solve the equation set up in the function vonKarman. Of course, it is possible to call Fortran code that does not access the IMSL routines. In that case, the Use IMSL statement would not be required. The setup for C/C++ code would be similar. Microsoft Visual C++ could be used for this. D. Clough 3/8/01
-3-