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.

.: 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

Sub ClearFilterListOrTable()
    Dim ACell As Range
    Dim ActiveCellInTable As Boolean

    'Check to see if the worksheet is protected.
    If ActiveSheet.ProtectContents = True Then
        MsgBox "This macro will not work when the worksheet is write-protected.", _
               vbOKOnly, "Clear filter example"
        Exit Sub
    End 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 Next
    ActiveCellInTable = (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 Next
        ActiveSheet.ShowAllData
        On Error GoTo 0
    Else
        MsgBox "Select a cell in your list or table before you run the macro.", _
               vbOKOnly, "Clear filter example"
    End If
End Sub




brazilsalesforceeffectiveness@gmail.com

✔ Brazil SFE®Author´s Profile  Google+   Author´s Professional Profile   Pinterest   Author´s Tweets

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 Range
    Dim ActiveCellInTable As Boolean
    Dim FilterCriteria As String

    'Check to see if the worksheet is protected.
    If ActiveSheet.ProtectContents = True Then
        MsgBox "This macro will not work when the worksheet is write-protected.", _
               vbOKOnly, "Filter example"
        Exit Sub
    End 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 Next
    ActiveCellInTable = (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 Next
        ActiveSheet.ShowAllData
        On 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:="=" & FilterCriteria
    Else
        MsgBox "Select a cell in your list or table before you run the macro.", _
               vbOKOnly, "Filter example"
    End If
End Sub




Tags: Excel, VBA, cell, activecell, table, list, Copying, copy, Table, List, Worksheet, Workbook, filter




Inline image 1

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 Worksheet
    Dim ACell As Range
    Dim CCount As Long
    Dim ActiveCellInTable As Boolean
    Dim CopyFormats As Variant
    Dim sheetName As String

    'Verifique se a planilha ou pasta de trabalho está protegida.
    If ActiveWorkbook.ProtectStructure = True Or ActiveSheet.ProtectContents = True Then
        MsgBox "Esta macro não funcionará quando a pasta de trabalho ou planilha estiver protegida contra gravação."
        Exit Sub
    End 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 Next
    Let 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 Then
        With Application
            Let .ScreenUpdating = False
            Let .EnableEvents = False
        End 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 Next
        With ACell.ListObject.ListColumns(1).Range
            Let CCount = .SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
        End With
        On Error GoTo 0

        If CCount = 0 Then
            MsgBox "Há mais de 8192 áreas, de modo que não é possível
copiar 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 Next
            New_Ws.Name = sheetName
            If Err.Number > 0 Then
                MsgBox "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.Clear
            End If
            On Error GoTo 0

            'Paste the data into the new worksheet.
            With New_Ws.Range("A1")
                .PasteSpecial xlPasteColumnWidths
                .PasteSpecial xlPasteValuesAndNumberFormats
                .Select
                Let Application.CutCopyMode = False
            End With

            'Call the Create List or Table dialog.
            Let Application.ScreenUpdating = True
            Application.CommandBars.FindControl(ID:=7193).Execute
            New_Ws.Range("A1").Select

            Let ActiveCellInTable = False
            On Error Resume Next
            Let ActiveCellInTable = (New_Ws.Range("A1").ListObject.Name <> "")
            On Error GoTo 0

            Let Application.ScreenUpdating = False

            'Se você não criar uma tabela, você tem a opção de copiar os formatos.
            If ActiveCellInTable = False Then
                Application.GoTo ACell
                Let CopyFormats = MsgBox("Você também deseja copiar os formatos?", _
                                     vbOKCancel + vbExclamation, "Copy to new worksheet")
                If CopyFormats = vbOK Then
                    ACell.ListObject.Range.Copy
                    With New_Ws.Range("A1")
                        .PasteSpecial xlPasteFormats
                        Let Application.CutCopyMode = False
                    End With
                End If
            End If
        End If

        'Select the new worksheet if it is not active.
        Application.GoTo New_Ws.Range("A1")

        With Application
            Let .ScreenUpdating = True
            Let .EnableEvents = True
        End With

    Else
        MsgBox "Selecione uma célula na sua lista ou tabela antes de executar a macro.", _
               vbOKOnly, "Copy to new worksheet"
    End If
End Sub



Tags: Excel, VBA, cell, activecell, table, list, Copying, copy, Table, List, Worksheet, Workbook, ListObject




Inline image 1

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 Boolean
    Dim 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 Next
    Let ActiveCellInTable = (ACell.ListObject.Name <> "")
    On Error GoTo 0

    If ActiveCellInTable = True Then
        MsgBox "Esta célula (ActiveCell) é parte da tabela."
    Else
        MsgBox "Esta célula (ActiveCell) não é parte da tabela."
    End If
End 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




Inline image 1

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 B5
    Range("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 number
End Sub

TagsVBA, 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,


diHITT - Notícias