A semianalytical finite-element method (FEM) has been developed to simulate electromagnetic borehole resistivity measurements in a layered underground formation. A piecewise homogeneous structure is divided into several layers. Each layer is uniform in the longitudinal direction, and the distributions of geometry and material can be arbitrary on the transverse plane, or cross section, of the layer. To develop this semianalytical finite-element scheme, the standard functional corresponding to the vector wave equation is cast to a new form in the Hamiltonian system based on dual variables that are the transverse components of electric and magnetic fields on the cross section of the layer. The 2D finite elements are used to discretize the cross section, and a high-precision integration scheme based on the Riccati equations is used to exploit the longitudinal homogeneity in the layer. By transforming a 3D layered problem into a series of 2D problems, this semianalytical FEM can save a great amount of computational costs and meanwhile achieve a higher level of accuracy when compared with conventional finite-element schemes. The flexibility of this semianalytical method can be greatly increased by hybridization with conventional finite elements, and this strategy works well for layered structures with local inhomogeneities such as borehole washouts. Several tests, including near-bit resistivity measurement and wave propagation resistivity logging, verified the effectiveness of this semianalytical FEM.