Sub ClearFilterListOrTable()Dim ACell As RangeDim ActiveCellInTable As Boolean'Check to see if the worksheet is protected.If ActiveSheet.ProtectContents = True ThenMsgBox "This macro will not work when the worksheet is write-protected.", _vbOKOnly, "Clear filter example"Exit SubEnd If
'Set a reference to the ActiveCell named ACell. You can always use'ACell now to point to this cell, no matter where you are in the workbook.Set ACell = ActiveCell'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you'don't need to know the name of the table to work with it.On Error Resume NextActiveCellInTable = (ACell.ListObject.Name <> "")On Error GoTo 0
'If the cell is in a list or table, run the code.If ActiveCellInTable = True Then'Show all data in the table or list.On Error Resume NextActiveSheet.ShowAllDataOn Error GoTo 0ElseMsgBox "Select a cell in your list or table before you run the macro.", _vbOKOnly, "Clear filter example"End IfEnd Sub
Propósito
✔ Programação GLOBAL® - Quaisquer soluções e/ou desenvolvimento de aplicações pessoais, ou da empresa, que não constem neste Blog devem ser tratados como consultoria freelance. Queiram contatar-nos: brazilsalesforceeffectiveness@gmail.com | ESTE BLOG NÃO SE RESPONSABILIZA POR QUAISQUER DANOS PROVENIENTES DO USO DOS CÓDIGOS AQUI POSTADOS EM APLICAÇÕES PESSOAIS OU DE TERCEIROS.
Meni
.: Vitrine
Carregando artigos...
Views
Mostrando postagens com marcador Cell. Mostrar todas as postagens
Mostrando postagens com marcador Cell. Mostrar todas as postagens
VBA Excel - Limpando Filtros - Clearing Filters
VBA Excel - Filtrando Tabelas ou Listas - Filtering Tables or Lists
Calendário Compacto para 2014
O código a seguir filtra uma tabela ou lista. Para testá-lo usamos uma tabela semelhante à abaixo.
Basta digitar os dados e, em seguida, usar o procedimento descrito.
Sub FilterListOrTableData()Dim ACell As RangeDim ActiveCellInTable As BooleanDim FilterCriteria As String
'Check to see if the worksheet is protected.If ActiveSheet.ProtectContents = True ThenMsgBox "This macro will not work when the worksheet is write-protected.", _vbOKOnly, "Filter example"Exit SubEnd If'Set a reference to the ActiveCell named ACell. You can always use'ACell now to point to this cell, no matter where you are in the workbook.Set ACell = ActiveCell'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you'don't need to know the name of the table to work with it.On Error Resume NextActiveCellInTable = (ACell.ListObject.Name <> "")On Error GoTo 0
'If the cell is in a list or table, run the code.If ActiveCellInTable = True Then'Show all data in the table or list.On Error Resume NextActiveSheet.ShowAllDataOn Error GoTo 0'This example filters on the first column in the List/Table'(change the field if needed). In this case the Table starts'in A so Field:=1 is column A, field 2 = column B, ......'Use "<>" & filtercriteria if you want to exclude the criteria from the filter.FilterCriteria = InputBox("What text do you want to filter on?", _"Type in the filter item.")ACell.ListObject.Range.AutoFilter _Field:=1, _Criteria1:="=" & FilterCriteriaElseMsgBox "Select a cell in your list or table before you run the macro.", _vbOKOnly, "Filter example"End IfEnd Sub
Tags: Excel, VBA, cell, activecell, table, list, Copying, copy, Table, List, Worksheet, Workbook, filter

VBA Excel - Copiando uma tabela ou lista para uma nova planilha
Calendário Compacto para 2014
O procedimento a seguir copia somente as células visíveis numa tabela ou lista para uma nova planilha. Este código usa o objeto ListObject para representar a tabela ou lista. Um detalhe adicional deste procedimento é o de que o número de ocorrências são não-contíguas.
O Excel tem um limite de 8.192 áreas não contíguas que pode ser copiada para qualquer tabela. O código pergunta se deseja criar uma tabela com os novos dados sobre na nova planilha. Se cancelar esta caixa de diálogo, será perguntado se deseja copiar apenas os formatos de modo que o intervalo pareça profissional.
Sub CopyListOrTable2NewWorksheet()Dim New_Ws As WorksheetDim ACell As RangeDim CCount As LongDim ActiveCellInTable As BooleanDim CopyFormats As VariantDim sheetName As String'Verifique se a planilha ou pasta de trabalho está protegida.If ActiveWorkbook.ProtectStructure = True Or ActiveSheet.ProtectContents = True ThenMsgBox "Esta macro não funcionará quando a pasta de trabalho ou planilha estiver protegida contra gravação."Exit SubEnd If'Definir uma referência ao ActiveCell. Você sempre pode usar a ACell'ponto para esta célula, não importa onde você está na pasta de trabalho.Set ACell = ActiveCell'Teste para ver se ACell está em uma tabela ou lista. Note-se que, usando ACell.ListObject, você'Não é necessário saber o nome da tabela para trabalhar com ele.On Error Resume NextLet ActiveCellInTable = (ACell.ListObject.Name <> "")On Error GoTo 0'Se a célula está em uma lista ou tabela executar o código.If ActiveCellInTable = True ThenWith ApplicationLet .ScreenUpdating = FalseLet .EnableEvents = FalseEnd With'Testar se existem mais de 8192 áreas separadas. Excel suporta apenas'um máximo de 8.192 áreas não contíguas através de macros VBA e manual.On Error Resume NextWith ACell.ListObject.ListColumns(1).RangeLet CCount = .SpecialCells(xlCellTypeVisible).Areas(1).Cells.CountEnd WithOn Error GoTo 0If CCount = 0 ThenMsgBox "Há mais de 8192 áreas, de modo que não é possívelcopiar os dados visíveis para uma nova planilha. Dica: Classifique os seus dados antes de aplicar o filtro e tente esta macro novamente.", _vbOKOnly, "Copy to new worksheet"Else'Copy the visible cells.ACell.ListObject.Range.Copy'Add a new Worksheet.Set New_Ws = Worksheets.Add(after:=Sheets(ActiveSheet.Index))
'Prompt the user for the worksheet name.Let sheetName = InputBox("Qual é o nome da nova worksheet?", _"Name the New Sheet")
On Error Resume NextNew_Ws.Name = sheetNameIf Err.Number > 0 ThenMsgBox "Altere o nome da Aba : " & New_Ws.Name & _" manualmente após a macro está pronta. O nome da sheet" & _" digitada já existe ou você usou caracteres" & _" que não são permitidos."Err.ClearEnd IfOn Error GoTo 0'Paste the data into the new worksheet.With New_Ws.Range("A1").PasteSpecial xlPasteColumnWidths.PasteSpecial xlPasteValuesAndNumberFormats.SelectLet Application.CutCopyMode = FalseEnd With'Call the Create List or Table dialog.Let Application.ScreenUpdating = TrueApplication.CommandBars.FindControl(ID:=7193).ExecuteNew_Ws.Range("A1").Select
Let ActiveCellInTable = FalseOn Error Resume NextLet ActiveCellInTable = (New_Ws.Range("A1").ListObject.Name <> "")On Error GoTo 0Let Application.ScreenUpdating = False'Se você não criar uma tabela, você tem a opção de copiar os formatos.If ActiveCellInTable = False ThenApplication.GoTo ACellLet CopyFormats = MsgBox("Você também deseja copiar os formatos?", _vbOKCancel + vbExclamation, "Copy to new worksheet")If CopyFormats = vbOK ThenACell.ListObject.Range.CopyWith New_Ws.Range("A1").PasteSpecial xlPasteFormatsLet Application.CutCopyMode = FalseEnd WithEnd IfEnd IfEnd If'Select the new worksheet if it is not active.Application.GoTo New_Ws.Range("A1")With ApplicationLet .ScreenUpdating = TrueLet .EnableEvents = TrueEnd WithElseMsgBox "Selecione uma célula na sua lista ou tabela antes de executar a macro.", _vbOKOnly, "Copy to new worksheet"End IfEnd Sub
Tags: Excel, VBA, cell, activecell, table, list, Copying, copy, Table, List, Worksheet, Workbook, ListObject

VBA Excel - Verificando se a célula ativa está em uma tabela ou lista
Muitas vezes antes de executar outros comandos e funções, queremos garantir que a célula ativa esteja em uma tabela ou lista.
Os seguintes testes de código para essa condição exibe uma caixa de mensagem com os resultados.
Sub ActiveCellIsInTable()Dim ActiveCellInTable As BooleanDim ACell As Range'Set a reference to the ActiveCell named ACell. You can always use
'ACell now to point to this cell, no matter where you are in the workbook.Set ACell = ActiveCell'Test whether ACell is in a table.On Error Resume NextLet ActiveCellInTable = (ACell.ListObject.Name <> "")On Error GoTo 0If ActiveCellInTable = True ThenMsgBox "Esta célula (ActiveCell) é parte da tabela."ElseMsgBox "Esta célula (ActiveCell) não é parte da tabela."End IfEnd Sub
Se a célula ativa estiver numa tabela, podemos usar a seguinte declaração para apontar para a tabela inteira.
ACell.ListObject.Range
Você pode usar a seguinte instrução para fazer referência a uma tabela sem cabeçalho.
ACell.ListObject.DataBodyRange
Tags: Excel, VBA, cell, activecell, table, list

VBA Excel Basic - Como tornar os texto Maiúsculos - How To Change The Text To Upper Case Or Lower Case
Sim, mais tópicos voltados para quem está iniciando na utilização do VBA - Visual Basic for Application.
Neste exemplo aprenderemos a como tornar os texto maiúsculos ou minúsculos.
Sub sbExample5()Range("C2").Value = UCase(Range("C2").Value)Range("C3").Value = LCase(Range("C3").Value)End Sub
Tags: VBA, Excel, worksheet, workbook, cell, Maiúsculo, Change, Text, Upper Case, Lower Case,

VBA Excel Basic - Como inserir dados numa célula - How To Enter Data into a Cell
É importante deixar alguns tópicos neste Blog, que sejam voltados para quem está iniciando na utilização do VBA - Visual Basic for Application.
Sub sbExample2()'It will enter the data into B5Range("B5") = "Hello World! using Range"'You can also use Cell Object as shwon below B6:Cells(6, 2) = "Hello World! using Cell" 'Here 6 is Row number and 2 is Column numberEnd Sub
Tags: VBA, Basic, Excel, worskheet, Sheet, cell, célula, dados, Enter Data,

Excel Tips - Convertendo conteúdo notação A1 para L1C1 - Convert A1 notation to R1C1

A automação no MS Excel é uma forma de transformamos tempo em procedimentos.
Poupa muito o nosso tempo !
Invariavelmente ao automatizarmos um processo precisaremos fazer referências a diversos Ranges e isso pode ser simplificado internamente no nosso código se convertermos a nossa notação A1 para L1C1 (ou R1C1 em inglês).
O estilo de referência A1
Por padrão, o Excel usa o estilo de referência A1, que se refere a colunas com letras (A até IV, para um total de 256 colunas) e se refere a linhas como números (1 a 65.536). Essas letras e números são chamados de cabeçalhos de linha e coluna. Para se referir a uma célula, digite a letra da coluna seguida pelo número da linha. Por exemplo, D50 se refere à célula na interseção da coluna D com a linha 50. Para se referir a um intervalo de células, digite a referência para a célula que está no canto superior esquerdo do intervalo, digite dois-pontos (:) e, em seguida, digite a referência à célula que está no canto inferior direito do intervalo.
O estilo de referência L1C1
O Excel também pode usar o estilo de referência L1C1, na qual as linhas e as colunas na planilha são numeradas. O estilo de referência L1C1 é útil se você desejar contar (computar) as posições da linha e coluna no seu código VBA. No estilo L1C1, o Excel indica o local de uma célula com um "L" seguido de um número de linha e um "C" seguido de um número de coluna.
Como? Simples assim:
Range("$E$51").Address(ReferenceStyle:=xlR1C1)
ou
ActiveCell.Address(ReferenceStyle:=xlR1C1)
Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...
Tags: VBA, Excel, R1C1, L1C1, Range, address, cell, célula, endereço, convert, conversão, notation, notação,

Assinar:
Postagens (Atom)








