0
votes

I have used the program command in Stata quite a few times now.

Today, I am trying to teach myself how to create a program that uses input. I've tried looking at the syntax help file and at page 71 of these lecture slides I found on the internet, but I can't figure out how to do this.

I would appreciate it if you could show me some documentation that covers this specific topic thoroughly. Or just point out what I'm doing wrong below.

As you can see, all I want is to create a short program that checks whether a file exists in the specified folder (capture confirm file), but I want to display my own dialogue box if there is an error (window stopbox note) and if so, then exit the do file in an orderly manner (exit 601).

cap program drop checkfile
program checkfile
syntax varlist, folder(varname) file(varname)
capture confirm file "`folder'/`file'"
    if _rc == 601 {
        window stopbox note `"`file' is not in `folder'"' // creates a dialogue box for the error
        exit 601
    }
end

checkfile folder(C:\Users\User\Documents) file(NIDSw5.dta)

Returns the error:

factor-variable and time-series operators not allowed
r(101);

I'm not sure how to use syntax in order to get the folder path and file name. Note that these are usually strings, but I'm guessing that:

"`folder'/`file'"

will result in, for example, ""C:\Users\User\Documents"/"NIDSw5.dta"" if the input is done with quotation marks, so that's why I thought I should use the local(input) method.

Also note that I will use a global variable ($DataIN) instead of putting the folder path string there, and the file name contains a global variable appended onto a string.

Removing varlist, results in the error:

invalid syntax
r(197);

1

1 Answers

1
votes

The following works for me:

program checkfile
syntax, folder(string) file(string)
capture confirm file "`folder'/`file'"
if _rc == 601 {
    window stopbox note `"`file' is not in `folder'"' 
    exit 601
}
end

You then simply need to type:

checkfile, folder(C:\Users\User\Documents) file(NIDSw5.dta)

EDIT:

You can also do it without using options as follows:

program checkfile
capture confirm file "`1'/`2'"
if _rc == 601 {
    window stopbox note `"`2' is not in `1'"'
    exit 601
}
end

checkfile C:\Users\User\Documents NIDSw5.dta