Selecionando células não em branco no Excel com VBA
-
03-07-2019 - |
Pergunta
Eu estou apenas começando a mergulhar em VBA e eu bati um pouco de um obstáculo.
Eu tenho uma folha com 50 + colunas, 900 + linhas de dados. Eu preciso reformatar cerca de 10 dessas colunas e furá-los em uma nova pasta de trabalho.
Como faço para programaticamente selecionar cada célula não-branco em uma coluna de book1, executá-lo através de algumas funções, e soltar os resultados em book2?
Solução
O seguinte código VBA deve começar. Ele irá copiar todos os dados na pasta de trabalho original para um novo livro, mas ele vai ter adicionado 1 para cada valor, e todas as células em branco terá sido 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
Outras dicas
Eu sei que sou sou muito tarde sobre isso, mas aqui algumas amostras Úteis:
'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select
ou
'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
.value = .value
end with
Para encontrar a última linha usada na coluna, nunca confiar em LastCell, que não é confiável (que não é reposto após a exclusão de dados). Em vez disso, eu uso someting como
lngLast = cells(rows.count,3).end(xlUp).row
Se você está procurando a última linha de uma coluna, 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
Outros comandos que você vai precisar para se familiarizar com a copiar e colar comandos:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finalmente, você pode fazer referência planilhas em outras pastas de trabalho usando a seguinte sintaxe:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
Isso pode ser completamente fora da base, mas você não pode simplesmente copiar toda a coluna em uma nova planilha e, em seguida, classificar a coluna? Estou assumindo que você não precisa para manter a integridade da ordem.