es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Eliminar una fila en una tabla de Word si un cierto número de celdas están vacías y/o contienen un valor específico.

Tengo este código (adjunto abajo) que eliminará las filas de una tabla de Word si todas las celdas de las filas están vacías.

Sin embargo, tengo una tabla con ocho columnas, las primeras cuatro siempre contendrán texto. Las últimas cuatro contienen datos vinculados a un documento de Excel.

La pregunta es; ¿cómo hago que el código busque en las últimas cuatro (datos) columnas y SI las columnas están vacías y/o contienen un valor (como cero) ENTONCES eliminar la fila.

Cualquier ayuda será muy apreciada.

Gracias de antemano

Sub EliminarFilasVaciasYTablasEnUnaTabla()
  Dim objCell As Cell
  Dim nRowIndex As Integer, nRows As Integer, nColumns As Integer, nColumnIndex As Integer
  Dim varCellEmpty As Boolean

  Application.ScreenUpdating = False

  If Selection.Information(wdWithInTable) = False Then
    MsgBox ("¡Coloque el cursor dentro de una tabla primero!")
    Exit Sub
  Else
    With Selection.Tables(1)
      nRows = .Rows.Count
      For nRowIndex = nRows To 1 Step -1
        varCellEmpty = True
        For Each objCell In .Rows(nRowIndex).Cells
          If Len(objCell.Range.Text) > 2 Then
            varCellEmpty = False
            Exit For
          End If
        Next objCell
          If varCellEmpty = True Then
            .Rows(nRowIndex).Delete
          End If
      Next nRowIndex


    End With
  End If

  Set objCell = Nothing

  Application.ScreenUpdating = True
End Sub
Tags:  ,

Answer

  1. Avatar for davy.ai

    Para modificar el código para buscar y eliminar filas basadas en las últimas cuatro columnas (datos) estando vacías y/o conteniendo un valor como cero, necesitarás agregar un bucle adicional que recorra las columnas empezando desde la quinta columna (ya que las primeras cuatro columnas siempre contienen texto). Puedes agregar el siguiente código después del bucle existente “For Each objCell In .Rows(nRowIndex).Cells”:

    For nColumnIndex = 5 To .Columns.Count
        If Len(.Rows(nRowIndex).Cells(nColumnIndex).Range.Text) > 2 And IsNumeric(.Rows(nRowIndex).Cells(nColumnIndex).Range.Text) And Not .Rows(nRowIndex).Cells(nColumnIndex).Range.Text = "0" Then
            varCellEmpty = False
            Exit For
        End If
    Next nColumnIndex
    

    Este bucle verifica si la celda en la fila y columna actual no está vacía y contiene un valor numérico distinto de cero. Si lo hace, establece varCellEmpty como False y sale del bucle. Si ninguna de las celdas en las últimas cuatro columnas contiene un valor numérico no vacío, varCellEmpty permanece como True y la fila se elimina.

    Ten en cuenta que puedes ajustar la verificación de valores numéricos no vacíos cambiando los criterios en la declaración “If”. En este momento, verifica si la longitud del texto de la celda es mayor a 2 (lo cual asume que la celda contiene al menos un carácter distinto de espacio en blanco). Puedes cambiar esto a un valor diferente o agregar criterios adicionales según tus necesidades.

    El código modificado se vería así:

    Sub DeleteBlankRowsAndTablesInATable()
      Dim objCell As Cell
      Dim nRowIndex As Integer, nRows As Integer, nColumns As Integer, nColumnIndex As Integer
      Dim varCellEmpty As Boolean
    
      Application.ScreenUpdating = False
      If Selection.Information(wdWithInTable) = False Then
        MsgBox ("¡Coloca el cursor dentro de una tabla primero!")
        Exit Sub
      Else
        With Selection.Tables(1)
          nRows = .Rows.Count
          For nRowIndex = nRows To 1 Step -1
            varCellEmpty = True
            For Each objCell In .Rows(nRowIndex).Cells
              If Len(objCell.Range.Text) > 2 And Not objCell.ColumnIndex <= 4 Then
                For nColumnIndex = 5 To .Columns.Count
                    If Len(.Rows(nRowIndex).Cells(nColumnIndex).Range.Text) > 2 And IsNumeric(.Rows(nRowIndex).Cells(nColumnIndex).Range.Text) And Not .Rows(nRowIndex).Cells(nColumnIndex).Range.Text = "0" Then
                        varCellEmpty = False
                        Exit For
                    End If
                Next nColumnIndex
                If Not varCellEmpty Then Exit For
              ElseIf Len(objCell.Range.Text) > 2 Then
                varCellEmpty = False
                Exit For
              End If
            Next objCell
              If varCellEmpty = True Then
                .Rows(nRowIndex).Delete
              End If
          Next nRowIndex
        End With
      End If
      Set objCell = Nothing
      Application.ScreenUpdating = True
    End Sub
    

    El código modificado también incluye una verificación para las primeras cuatro columnas que siempre contienen texto, para que no se eliminen filas si solo esas columnas contienen valores no vacíos.

Comments are closed.