Merged cells 'No node at given position' error

Hello, I wrote some code to style the first two cells of a table. In a regular table, styling works fine. But when I merge cells, I get a RangeError: 'No node at given position' error. I’ve been trying to solve this for a day and a half and still not getting anywhere. I don’t understand why it can’t find the second node. Please help. Thanks ezgif.com-gif-maker (1)

console.log('tableStartPos: ', tableStartPos, 'tableEndPos', tableEndPos)
if (tableStartPos && tableEndPos)
  for (let pos = tableStartPos; pos < tableEndPos; pos++)
    if (
      state.doc.nodeAt(pos)?.type.name === 'tableHeader' ||
      state.doc.nodeAt(pos)?.type.name === 'tableCell'
    ) {
      count++
      console.log('About to style node: ', this.editor.state.doc.nodeAt(pos), 'Pos: ', pos)
      this.editor.view.dispatch(this.editor.view.state.tr.setNodeMarkup(pos, undefined, {
        //style: newStyles,
        style: 'border: 3px dashed #0100ff; ',
      }))
      console.log('Styled node', this.editor.view.state.doc.nodeAt(pos), 'Pos: ', pos)
      if (count === 2)
        break
    }