Saltar al contenido

Error al borrar un rango vba


Recommended Posts

publicado

Buenas Noches

Tengo el siguiente código, que almacena las referencias de las celdas en la Variable Rango, para posteriormente borrar el contenido de las celdas.

El problema es que al llegar a la parte del borrado del Rango me Arroja error 1004 en tiempo de ejecución.

Son aproximadamente 100 celdas las que debe borrar.

Sub Factura_LimpiarPlantilla()

Dim Rango

Plantilla = "Factura_Registro"

Setup = "Factura_Setup"

Application.ScreenUpdating = False

Application.Calculation = xlCalculationManual

Sheets(Plantilla).Unprotect Clave

I = 2

Rango = ""

While Sheets(Setup).Cells(I, 3) <> ""

If Sheets(Setup).Cells(I, 5) = "SI" Then

Celda = Sheets(Setup).Cells(I, 3)

If Rango = "" Then Rango = Celda Else Rango = Rango & "," & Celda

End If

I = I + 1

Wend

Sheets(Plantilla).Range(Rango) = Empty

Sheets(Plantilla).Protect Clave

Application.Calculation = xlCalculationAutomatic

Application.ScreenUpdating = True

End Sub

publicado

Bueno, al parecer excel no permite borrar mediante la propiedad Range = Empty hasta cierto número de celdas, por lo cual intenté usé 3 variables de rango para almacenar las celdas a borrar y funcionó.

Si alguien tiene una mejor solución se lo agradecería

publicado

.

Sheets(Plantilla).Range(Rango) = Empty es perfectamente válido siempre que la variable Plantilla contenga el nombre de una hoja existente en el libro y la variable Rango contenga la dirección de uno o varios rangos de celdas.

Lo ortodoxo sería Sheets(Plantilla).Range(Rango).Value = Empty, aunque en el objeto Range la propiedad .Value se asume por defecto.

Tu error ha sido almacenar en la variable Rango el valor de las celdas y no su dirección.

Así funcionará hasta un máximo de 64 celdas, luego te dará un error 1004.

If Rango = "" Then Rango = Celda.Address Else Rango = Rango & "," & Celda.Address

Por eso yo te recomiendo trabajar con objetos y no con direcciones:

Sub Factura_LimpiarPlantilla()
Dim Rango As Range
Dim Plantilla As Worksheet
Dim Setup As Worksheet

Set Plantilla = Sheets("Factura_Registro")
Set Setup = Sheets("Factura_Setup")

Application.ScreenUpdating = False
Plantilla.Unprotect Clave

I = 2
While Setup.Cells(I, 3) <> ""
If Setup.Cells(I, 5) = "SI" Then
If Rango Is Nothing Then
Set Rango = Setup.Cells(I, 3)
Else
Rango = Application.Union(Rango, Setup.Cells(I, 3))
End If
End If
I = I + 1
Wend

If Not Rango Is Nothing Then Rango = Empty
Plantilla.Protect Clave
Application.ScreenUpdating = True

End Sub
[/CODE]

[/color]

[color=#000000]O aunque mas lento, pero mas sencillo:[/color]

[color=rgb(0, 0, 255)]

[CODE]Sub Factura_LimpiarPlantilla()

Dim Plantilla As Worksheet
Dim Setup As Worksheet

Set Plantilla = Sheets("Factura_Registro")
Set Setup = Sheets("Factura_Setup")

Application.ScreenUpdating = False
Plantilla.Unprotect Clave

I = 2
While Setup.Cells(I, 3) <> ""
If Setup.Cells(I, 5) = "SI" Then
Setup.Cells(I, 3) = Empty
I = I + 1
Wend

Plantilla.Protect Clave
Application.ScreenUpdating = True

End Sub
[/CODE]

[/color]

.

PD: [color=#ff0000]Como no has subido el archivo, tal como indican las normas, los códigos no han sido probados.

.[/color]

[/b]

publicado

@[uSER=7340]marco antonio[/uSER]

Gracias por tu respuesta, pero ese no es el problema.

Me explicaré mejor,

En la Hoja Setup en la Columna 3, tengo almacenadas las direcciones de las celdas.

La variable Celda lo que hace es traer esa dirección (ejem A1, B5)

En la Variable Rango voy almacenando todas las direcciones ejem (A1,B5,H9)

El problema Radica que al utilizar Sheets(Plantilla).Range(Rango)=Emtpy el sistema arroja error porque al parecer el rango que quiero borrar es demasiado extenso.

Rango toma el siguiente valor al ejecutar la marco

Rango = N5,U5,B5,G8,G10,K14,G15,G17,G19,G21,G23,G25,P8,C29,E29,O29,Q29,S29,V29,X29,C30,E30,O30,Q30,S30,V30,X30,C31,E31,O31,Q31,S31,V31,X31,C32,E32,O32,Q32,S32,V32,X32,C33,E33,O33,Q33,S33,V33,X33,C34,E34,O34,Q34,X34,S34,V34,C35,E35,O35,Q35,S35,V35,X35,C36,E36,O36,Q36,S36,V36,X36,C37,E37,O37,Q37,S37,V37,X37,C38,E38,O38,Q38,S38,V38,X38,X41,X42,E43,N43,E45,H45,J45,O45,E46,H46,J46,O46,E47,H47,J47,O47,E48,H48,J48,O48

publicado

.

Ya te lo he explicado en el post anterior:

Así funcionará hasta un máximo de 64 celdas, luego te dará un error 1004.

Y también te he dado la solución:

Por eso yo te recomiendo trabajar con objetos y no con direcciones:

Te dejo la macro modificada para tomar las direcciones de las celdas de la columna 3.

Sub Factura_LimpiarPlantilla()
Dim Rango As Range
Dim Plantilla As Worksheet
Dim Setup As Worksheet

Set Plantilla = Sheets("Factura_Registro")
Set Setup = Sheets("Factura_Setup")

Application.ScreenUpdating = False
Plantilla.Unprotect Clave

I = 2
While Setup.Cells(I, 3) <> ""
If Setup.Cells(I, 5) = "SI" Then
If Rango Is Nothing Then
Set Rango = Setup.Range(Setup.Cells(I, 3).Value)
Else
Set Rango = Application.Union(Rango, Setup.Range(Setup.Cells(I, 3).Value))
End If
End If
I = I + 1
Wend

If Not Rango Is Nothing Then Rango = Empty
Plantilla.Protect Clave
Application.ScreenUpdating = True
End Sub
[/CODE]

.

Archivado

Este tema está ahora archivado y está cerrado a más respuestas.

  • 109 ¿Te parecen útiles los tips de las funciones? (ver tema completo)

    1. 1. ¿Te parecen útiles los tips de las funciones?


      • No
      • Ni me he fijado en ellos

  • Ayúdanos a mejorar la comunidad

    • Donaciones recibidas este mes: 0.00 EUR
      Objetivo: 130.00 EUR
  • Archivos

  • Estadísticas de descargas

    • Archivos
      188
    • Comentarios
      98
    • Revisiones
      29

    Más información sobre "Cambios en el Control Horario"
    Última descarga
    Por pegones1

    4    1

  • Crear macros Excel

  • Mensajes

    • Hola, veo que tienes 365, así que esta forma funcionará   Almacen.xlsx
    • Buenos días  @LeandroA espero estes bien Tengo un caso idéntico al planteado en la siguiente pregunta: Sin embargo, a diferencia de quien planteo originalmente la pregunta al correr el código no obtengo ningún resultado podrían ayudarme a resolver este inconveniente y que al hacer click en el Botón Guardar (CommandButton3) del Formulario RCS (frmrcs) el archivo pdf quede configurado con orientación vertical, márgenes superior, inferior, derecho e izquierdo = 1 y en página tamaño carta. Si acaso influye uso Microsoft Excel LTSC MSO (versión 2209 Compilación16.0.1.15629.20200) de 64 bits Mucho le sabre agradecer la ayuda que me pueda dar  RCS PRUEBA - copia.xlsm
    • @JSDJSDCon gusto mi estimado Para la opción 1: Sub Surtirhastadondealcanse() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets(1) Dim filaInicio As Integer: filaInicio = 4 Dim filaFin As Integer: filaFin = 7 Dim colInventario As Integer: colInventario = 2 Dim colSolicitudesInicio As Integer: colSolicitudesInicio = 4 ' Columna C Dim colResultadoInicio As Integer: colResultadoInicio = 9 ' Columna I Dim colTotalSurtido As Integer: colTotalSurtido = 12 ' Columna L Dim colFinalInventario As Integer: colFinalInventario = 13 ' Columna M Dim numClientes As Integer: numClientes = 3 Dim fila As Integer, i As Integer For fila = filaInicio To filaFin Dim inventario As Double inventario = Val(ws.Cells(fila, colInventario).Value) Dim solicitudes(1 To 3) As Double Dim surtido(1 To 3) As Variant Dim totalSurtido As Double: totalSurtido = 0 ' Leer solicitudes For i = 1 To numClientes If IsNumeric(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) Then solicitudes(i) = CDbl(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) Else solicitudes(i) = 0 End If surtido(i) = "POR FALTA STOCK" Next i ' Surtir de acuerdo al inventario disponible For i = 1 To numClientes If solicitudes(i) > 0 Then If inventario >= solicitudes(i) Then surtido(i) = solicitudes(i) inventario = inventario - solicitudes(i) totalSurtido = totalSurtido + solicitudes(i) ElseIf inventario > 0 Then surtido(i) = inventario totalSurtido = totalSurtido + inventario inventario = 0 Else surtido(i) = "POR FALTA STOCK" End If End If Next i ' Escribir resultados en las columnas correspondientes para cada cliente For i = 1 To numClientes With ws.Cells(fila, colResultadoInicio + i - 1) If surtido(i) = "POR FALTA STOCK" Then .Value = surtido(i) .Font.Color = vbRed Else .Value = surtido(i) .Font.Color = vbBlack End If End With Next i ' Escribir total surtido y existencia final ws.Cells(fila, colTotalSurtido).Value = totalSurtido ws.Cells(fila, colFinalInventario).Value = inventario Next fila MsgBox "Resultado surtido cargado con éxito...", vbInformation End Sub Para la opción 2:   Sub surtirenpartesiguales() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets(1) Dim filaInicio As Integer: filaInicio = 13 Dim filaFin As Integer: filaFin = 16 Dim colInventario As Integer: colInventario = 2 Dim colSolicitudesInicio As Integer: colSolicitudesInicio = 4 ' Columna C Dim colResultadoInicio As Integer: colResultadoInicio = 9 ' Columna I Dim colTotalSurtido As Integer: colTotalSurtido = 12 ' Columna L Dim colFinalInventario As Integer: colFinalInventario = 13 ' Columna M Dim numClientes As Integer: numClientes = 3 Dim fila As Integer, i As Integer For fila = filaInicio To filaFin Dim inventario As Double inventario = Val(ws.Cells(fila, colInventario).Value) Dim solicitudes(1 To 3) As Double Dim surtido(1 To 3) As Variant Dim totalSurtido As Double: totalSurtido = 0 Dim totalPedido As Double: totalPedido = 0 ' Leer solicitudes For i = 1 To numClientes If IsNumeric(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) Then solicitudes(i) = CDbl(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) totalPedido = totalPedido + solicitudes(i) Else solicitudes(i) = 0 End If surtido(i) = 0 Next i ' Si hay suficiente inventario, surtir lo que el cliente pide If inventario >= totalPedido Then For i = 1 To numClientes If solicitudes(i) > 0 And inventario >= solicitudes(i) Then surtido(i) = solicitudes(i) inventario = inventario - solicitudes(i) totalSurtido = totalSurtido + solicitudes(i) End If Next i Else ' Reparto base igualitario Dim baseSurtido As Long baseSurtido = Int(inventario / numClientes) For i = 1 To numClientes If solicitudes(i) > 0 Then If solicitudes(i) <= baseSurtido Then surtido(i) = solicitudes(i) inventario = inventario - solicitudes(i) totalSurtido = totalSurtido + solicitudes(i) Else surtido(i) = baseSurtido inventario = inventario - baseSurtido totalSurtido = totalSurtido + baseSurtido End If End If Next i ' Repartir sobrante restante uno por uno, respetando lo pedido Do While inventario > 0 For i = 1 To numClientes If surtido(i) < solicitudes(i) Then surtido(i) = surtido(i) + 1 totalSurtido = totalSurtido + 1 inventario = inventario - 1 If inventario = 0 Then Exit For End If Next i Loop End If ' Escribir resultados en las columnas correspondientes para cada cliente For i = 1 To numClientes With ws.Cells(fila, colResultadoInicio + i - 1) If surtido(i) = 0 Then .Value = "POR FALTA STOCK" .Font.Color = vbRed Else .Value = surtido(i) .Font.Color = vbBlack End If End With Next i ' Escribir total surtido y existencia final ws.Cells(fila, colTotalSurtido).Value = totalSurtido ws.Cells(fila, colFinalInventario).Value = inventario Next fila MsgBox "Resultado surtido cargado con éxito...", vbInformation End Sub Saludos, Diego
    • Buenos dias.  Estoy trabajando en una hoja para poder llevar un control de un pequeño almacén.  Tengo un pedido con varias líneas y "lotes" y necesito sacar las ubicaciones que coincidan con la referencia y lote que pone en el pedido. El problema viene cuando tengo la misma referencia y mismo lote en ubicaciones diferentes y necesito sacar la información en columnas diferentes. No se si  me he explicado bien, pero creo que con el ejemplo adjunto se entiende mejor. Agradecería mucho si me pudieran ayudar  Libro1.xlsx
    • Exelente solución mil gracias 
  • Visualizado recientemente

    • No hay usuarios registrado para ver esta página.
×
×
  • Crear nuevo...

Información importante

Echa un vistazo a nuestra política de cookies para ayudarte a tener una mejor experiencia de navegación. Puedes ajustar aquí la configuración. Pulsa el botón Aceptar, si estás de acuerdo.