Batch command variables used inside for loop is not readable outside [duplicate]

  batch-file, cmd, delayedvariableexpansion, windows

This batch file I am creating is to find most recent 2 text files based on creation time if windows environment variable is set to a number. Below is the batch code I created. However, I found commands (line 15 to 22) are not doing what I am asking. What am I missing here?

echo off
setlocal enableDelayedExpansion
if defined APP(
    Set APPNUM=%APP:~0,6%
) else (
    Set APPNUM=-NA-
if {%APPNUM%}=={1111} ( 
    set /a ID=1
    for /f "delims=" %%G in ('dir D:*.txt /b/a-d/od/t:c') do (
        set filename[!ID!]=%%~G
        set /a ID+=1      
    set /a latestIndx=!ID!-1
    set /a secondLatestIndx=!ID!-2
    set filename 
    echo There are !ID!
    set lastestFileName=!filename[%latestIndx%]!
    set secondLatestFileName=!filename[%secondLatestIndx%]!
    echo Lastest file is !lastestFileName!
    echo Second lastest file is !secondLatestFileName!

The output looks like below:

There are 4
Lastest file is
Second lastest file is

Source: Windows Questions