You have not posted a complete program - you should always do so.
Also please post your program using the code button </>
so it looks like this
. See How to use the Forum. It makes it much easier for people to help you
If that was my project I would have a variable to keep track of the required direction and it would be changed whenever a limit switch is pressed. Then the motor code would take account of that. Something like this pseudo code
void loop() {
checkSwitches();
moveMotor();
}
void checkSwitches() {
if (leftLimitSwitch is pressed) {
motorDirection = 'R';
}
if (rightLimitSwitch is pressed) {
motorDirection = 'L';
}
}
void moveMotor() {
if motorDirection == 'R'
stepRight
}
else {
stepLeft
}
}
...R