Selección de celdas no en blanco en Excel con VBA
-
03-07-2019 - |
Pregunta
Estoy empezando a sumergirme en VBA y he golpeado un poco como un obstáculo.
Tengo una hoja con más de 50 columnas, más de 900 filas de datos. Necesito reformatear alrededor de 10 de esas columnas y pegarlas en un nuevo libro de trabajo.
¿Cómo selecciono mediante programación cada celda que no está en blanco en una columna de book1, la ejecuto a través de algunas funciones y descarto los resultados en book2?
Solución
El siguiente código de VBA debería ayudarte a comenzar. Copiará todos los datos en el libro de trabajo original a un libro de trabajo nuevo, pero habrá agregado 1 a cada valor, y todas las celdas en blanco se habrán ignorado.
Option Explicit
Public Sub exportDataToNewBook()
Dim rowIndex As Integer
Dim colIndex As Integer
Dim dataRange As Range
Dim thisBook As Workbook
Dim newBook As Workbook
Dim newRow As Integer
Dim temp
'// set your data range here
Set dataRange = Sheet1.Range("A1:B100")
'// create a new workbook
Set newBook = Excel.Workbooks.Add
'// loop through the data in book1, one column at a time
For colIndex = 1 To dataRange.Columns.Count
newRow = 0
For rowIndex = 1 To dataRange.Rows.Count
With dataRange.Cells(rowIndex, colIndex)
'// ignore empty cells
If .value <> "" Then
newRow = newRow + 1
temp = doSomethingWith(.value)
newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
End If
End With
Next rowIndex
Next colIndex
End Sub
Private Function doSomethingWith(aValue)
'// This is where you would compute a different value
'// for use in the new workbook
'// In this example, I simply add one to it.
aValue = aValue + 1
doSomethingWith = aValue
End Function
Otros consejos
Sé que llego muy tarde a esto, pero aquí hay algunos ejemplos útiles:
'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select
o
'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
.value = .value
end with
Para encontrar la última fila utilizada en la columna, nunca confíe en LastCell, que no es confiable (no se restablece después de eliminar datos). En su lugar, utilizo algo como
lngLast = cells(rows.count,3).end(xlUp).row
Si está buscando la última fila de una columna, use:
Sub SelectFirstColumn()
SelectEntireColumn (1)
End Sub
Sub SelectSecondColumn()
SelectEntireColumn (2)
End Sub
Sub SelectEntireColumn(columnNumber)
Dim LastRow
Sheets("sheet1").Select
LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub
Otros comandos con los que deberá familiarizarse son los comandos de copiar y pegar:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finalmente, puede hacer referencia a las hojas de trabajo en otros libros de trabajo utilizando la siguiente sintaxis:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
Esto podría estar completamente fuera de base, pero ¿no puedes simplemente copiar toda la columna en una nueva hoja de cálculo y luego ordenar la columna? Supongo que no es necesario mantener la integridad del pedido.