Context. In June 2021 the discovery of an unusual comet C/2014 UN 271 Bernardinelli-Bernstein has been announced. Its cometary activity beyond Uranus orbit also has refreshed interest in similar objects, including C/2017K2 PanSTARRS. Another peculiarity of these objects is the long interval of positional data, taken at large heliocentric distances. Aims. These two comets are suitable candidates for a detailed investigation of their long-term motion outside the planetary zone. Using the carefully selected orbital solutions, we aim at estimating the orbital parameters of their orbits at the previous perihelion passage. This might allow us to discriminate between dynamically old and new comets. Methods. To follow the dynamical evolution of long-period comets far outside the planetary zone, it is necessary to take into account both the perturbation caused by the overall Galactic gravitational potential and the actions of individual stars appearing in the solar neighborhood. To this aim, we applied the recently published methods based on stellar perturbers ephemerides. Results. For C/2014 UN 271 we obtained a precise orbital solution that can be propagated to the past and to the future. For C/2017 K2 we have to limit ourselves to study only the past motion since some signs of nongravitational effects can be found in recent positional observations. Therefore, we use a specially selected orbital solution suitable for past motion studies. Using these starting orbits, we propagated both comets to their previous perihelia. We also investigated the future motion of C/2014 UN 271 . Conclusions. Orbital evolution of these two comets appears to be sensitive to perturbations from several stars that closely approach the Sun. Unfortunately, some of these stars have 6D data with uncertainties too large to obtain definitive results for the studied comets; however, it appears that both comets were probably outside the planetary zone in the previous perihelion.