Published on :
Macro EXTERNAL

Macro to Count Variables

This code is also available in: Deutsch Español Français
This macro, named `vdo_numvar`, is designed for reusability to easily determine the number of variables present in any SAS© dataset. It takes a single argument, `dsn`, which represents the full name (or referenced via libname) of the target dataset.
Internally, it uses the SAS© `%sysfunc` function to perform the following operations:
1. `open(&dsn)`: Opens the dataset specified by `dsn` and returns its dataset ID (`dsid`).
2. `attrn(&dsid,nvars)`: Retrieves the numeric attribute 'nvars' (number of variables) of the dataset identified by `dsid`.
3. `close(&dsid)`: Closes the dataset to release resources.
The macro directly returns the numeric value corresponding to the number of variables found. It is useful for dynamic programming where the number of variables may vary and needs to be known for subsequent processing.
Data Analysis

Type : EXTERNAL


The macro operates on an existing SAS dataset whose name is passed as a parameter (`&dsn`). The specific origin of this dataset is not defined within the macro itself; it could be SASHELP data, data previously created in the session, or external data referenced via a libname.

1 Code Block
MACRO
Explanation :
This block defines the `vdo_numvar` macro. It opens the dataset specified by the `dsn` parameter, uses the `attrn` function to retrieve the number of variables (`nvars`), and then closes the dataset. The direct result of the macro is the number of variables.
Copied!
1macro vdo_numvar(dsn)/des="Nnmber of variables in a SAS dataset";
2 
3%let dsid=%sysfunc(open(&dsn));
4%sysfunc(attrn(&dsid,nvars)) %let rc=%sysfunc(close(&dsid));
5 
6%mend vdo_numvar;
7 
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.