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 Linha. Mostrar todas as postagens
Mostrando postagens com marcador Linha. Mostrar todas as postagens

VBA Access - Quebra uma Linha a partir de um caracter - BreakTextAtX

Esta função tem a capacidade de inserir quebras nas linhas, a partir de um carácter identificado.

Function BreakTextAtX (varOriginal As Variant, _
      Optional strBreakCharacter As String = " ", _
      Optional lngMaxLength As Long = 72) As Variant

Dim strNewString As String, strWorking As String, strPart As String
Dim strOriginalNoCrLf As String
Dim lngPosition As Long, lngHold As Long, lngLength As Long
Dim lngWorkLength As Long

lngLength = Len(varOriginal & "")

If lngLength > 0 Then
      Let strOriginalNoCrLf = Replace(Replace(CStr(varOriginal), vbCr, ""), _
            vbLf, "")
      Let strNewString = ""
      Let lngPosition = 1
      Do While lngPosition <= lngLength
            Let strWorking = Mid(strOriginalNoCrLf, lngPosition, lngMaxLength)
            Let lngWorkLength = Len(strWorking)
            If lngWorkLength < lngMaxLength Then
                  If Len(strNewString) > 0 And Len(strWorking) > 0 Then _
                        Let strNewString = strNewString & vbCrLf
                  Let strNewString = strNewString & strWorking
                  Exit Do
            Else
                  Let lngHold = InStrRev(strWorking, strBreakCharacter)
                  If lngHold = 0 Then lngHold = lngWorkLength
                  If Len(strNewString) > 0 Then _
                        Let strNewString = strNewString & vbCrLf
                  Let strNewString = strNewString & Left(strWorking, lngHold)
                  Let lngPosition = lngPosition + lngHold
            End If
      Loop
      Let BreakTextAtX = strNewString

Else
      If IsNull(varOriginal) = True Then
            Let BreakTextAtX = varOriginal
      Else
            Let BreakTextAtX = ""
      End If

End If
End Function


Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...

Tags: Access, break, 72, quebra, linha, insere, carriage return, character,line feed,


Inline image 1


VBA Excel - Definindo a última linha - How To Delete Rows

Recebi um monte de perguntas sobre qual o melhor modo de excluirmos linhas no MS Excel, dadas várias condições. 

Montei alguns exemplos que devem ajudá-los a começar caso precisem enfrentar tal tarefa. 

Este post é uma coletânea de exemplos de código VBA - não um tutorial.

Determinando a última linha usada

Use este código ao longo da linha para determinar a última linha com dados num intervalo especificado:

Public Function GetLastRow (ByVal rngToCheck As Range) As Long

    Dim rngLast As Range
    
    Set rngLast = rngToCheck.Find(what:="*", searchorder:=xlByRows, searchdirection:=xlPrevious)
    
    If rngLast Is Nothing Then
        Let GetLastRow = rngToCheck.Row
    Else
        Let GetLastRow = rngLast.Row
    End If
    
End Function

Exclua a linha se determinada célula, na coluna, estiver vazia

Este código é apenas uma 'carcaça' modelo que demonstra a maneira mais rápida e simples de excluirmos cada linha da Aba (Sheet1), se as células na coluna A estiverem vazias:

Sub Example1()

    Dim lngLastRow As Long
    Dim rngToCheck As Range

    Let Application.ScreenUpdating = False

    With Sheet1
        'if the sheet is empty then exit...
        If Application.WorksheetFunction.CountA(.Cells) > 0 Then

            'find the last row in the worksheet
            Let lngLastRow = GetLastRow(.Cells)
            
            Set rngToCheck = .Range(.Cells(1, 1), .Cells(lngLastRow, 1))
        
            If rngToCheck.Count > 1 Then
                'if there are no blank cells then there will be an error
                On Error Resume Next
                rngToCheck.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
                On Error GoTo 0
            Else
                If VBA.IsEmpty(rngToCheck) Then rngToCheck.EntireRow.Delete
            End If
        End If
    End With
    
    Let Application.ScreenUpdating = True

End Sub

Excluir linhas, se as células na mesma linha estiverem vazias

Este exemplo sobrepõe o anterior, mas apresenta outra nuance quando se trabalha com o método de intervalo do objeto SpecialCells. Este exemplo excluirá todas as linhas na planilha,quando qualquer uma das suas células nas colunas de B a E estiverem vazias. 


Sub Example1()

    Dim lngLastRow As Long
    Dim rngToCheck As Range, rngToDelete As Range

    Let Application.ScreenUpdating = False

    With Sheet1

        
        'find the last row on the sheet
        Let lngLastRow = GetLastRow(.Cells)
        
        If lngLastRow > 1 Then
            'we want to check the used range in columns B to E
            'except for our header row which is row 1
            Set rngToCheck = .Range(.Cells(2, "b"), .Cells(lngLastRow, "e"))
        
            'if there are no blank cells then there will be an error
            On Error Resume Next
            Set rngToDelete = rngToCheck.SpecialCells(xlCellTypeBlanks)
            On Error GoTo 0
            
            'allow for overlapping ranges
            If Not rngToDelete Is Nothing Then _
                    Application.Intersect(.Range("A:A"), rngToDelete.EntireRow).EntireRow.Delete
        End If
    End With
    
    Let Application.ScreenUpdating = True
End Sub

Use o objeto Range para encontrar Método

A abordagem mais tradicional para resolver esta tarefa é percorrer toda a coluna, verificar se cada célula contém o valor e, se isso acontecer, excluir a linha. Como o Excel desloca as linhas para cima quando forem excluídas, é melhor começarmos na parte inferior da coluna.

Sub Example1()

    Const strTOFIND As String = "Hello"

    Dim rngFound As Range, rngToDelete As Range
    Dim strFirstAddress As String
    
    Let Application.ScreenUpdating = False
    
    With Sheet1.Range("A:A")
        Set rngFound = .Find( _
                            What:=strTOFIND, _
                            Lookat:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=True)
        
        If Not rngFound Is Nothing Then
            Set rngToDelete = rngFound

            'note the address of the first found cell so we know where we started.
            strFirstAddress = rngFound.Address
            
            Set rngFound = .FindNext(After:=rngFound)
            
            Do Until rngFound.Address = strFirstAddress
                Set rngToDelete = Application.Union(rngToDelete, rngFound)
                Set rngFound = .FindNext(After:=rngFound)
            Loop
        End If
    End With
    
    If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete
    
    Let Application.ScreenUpdating = True

End Sub

Usando o método Range com o Autofiltro

Claro, este procedimento pressupõe que a Linha 1 contém cabeçalhos de campo.


Sub Example2()

    Const strTOFIND As String = "Hello"
    
    Dim lngLastRow As Long
    Dim rngToCheck As Range
    
    Let Application.ScreenUpdating = False

    
    With Sheet1
        'find the last row in the Sheet
        Let lngLastRow = GetLastRow(.Cells)
        
        Set rngToCheck = .Range(.Cells(1, 1), .Cells(lngLastRow, 1))
    End With
    
    With rngToCheck
        .AutoFilter Field:=1, Criteria1:=strTOFIND
        
        'assume the first row had headers
        On Error Resume Next
        .Offset(1, 0).Resize(.Rows.Count - 1, 1). _
            SpecialCells(xlCellTypeVisible).EntireRow.Delete
        On Error GoTo 0
        
        'remove the autofilter
        .AutoFilter
    End With

    Let Application.ScreenUpdating = True

End Sub

Usando o objeto Range com o método ColumnDifferences

o código abaixo é muito semelhante ao anterior, exceto pela aplicação de uma lógica inversa. Apesar de invertemos a lógica do Range.Autofilter a abordagem será bem simples, está ligeiramente diferente com o método Range.Find.

Sub Example1()
    Const strTOFIND As String = "Hello"

    Dim lngLastRow As Long
    Dim rngToCheck As Range
    Dim rngFound As Range, rngToDelete As Range
    
    Let Application.ScreenUpdating = False
    
    With Sheet1
        Let lngLastRow = GetLastRow(.Cells)
        
        If lngLastRow > 1 Then
            'we don't want to delete our header row
            With .Range("A2:A" & lngLastRow)
            
                Set rngFound = .Find( _
                                    What:=strTOFIND, _
                                    Lookat:=xlWhole, _
                                    SearchOrder:=xlByRows, _
                                    SearchDirection:=xlNext, _
                                    MatchCase:=True)
            
                If rngFound Is Nothing Then
                    'there are no cells we want to keep!
                    .EntireRow.Delete                    
                Else            
                    'determine all the cells in the range which have a different value
                    On Error Resume Next
                    Set rngToDelete = .ColumnDifferences(Comparison:=rngFound)
                    On Error GoTo 0
                    
                    If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete
                    
                End If
            End With
        End If
    End With
    
    Let Application.ScreenUpdating = True
End Sub


Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...


Tags: VBA, Excel, last, row, última, linha, getlastrow, 


VBA Excel Basic - Configurando Altura da Linha e Largura da Coluna - How To Set The Row Height And Column Width



Sim, este é mais um tópico voltado para quem está iniciando na utilização do VBA - Visual Basic for Application no MS Excel.

Quando colamos dados em um relatório, invariavelmente queremos formatar o layout desses dados. Aqui, aprendemos como automatizar o acerto das Linhas e Colunas onde os nossos dados ficarão.

Ajustar a altura das Linhas e a Largura das Colunas, fará com que os dados analisados fiquem mais compreensíveis aos usuários que os analisarão.

Sub sbExample13()
    
    Rows(12).RowHeight = 33
    Columns(5).ColumnWidth = 35
End Sub



Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...


Tags: VBA, Excel, worksheet, workbook, Rows, Columns, Height, Column, largura, altura, linha, coluna, planilha, pasta,


VBA Excel - Deletando linhas duplicadas - Delete duplicate rows


Public Sub DelDupliRows (rng As Range)' Author:                  Date:                   Contact:' André Bernardes 29/01/2009 12:18 bernardess@gmail.com' Esta SUB deletará registros (linhas) duplicadas, será baseada no Range passado' como parâmetro. Quando esta SUB achar mais duma ocorrência no mesmo Range,' todas as ocorrências seguintes serão deletadas.
Dim r As LongDim n As LongDim v As Variant
On Error GoTo EndMacro
Let Application.ScreenUpdating = FalseLet Application.Calculation = xlCalculationManualLet Application.StatusBar = "Linha sendo processada: " & _ Format(rng.Row, "#,##0")
Let n = 0
For r = rng.Rows.Count To 2 Step -1If r Mod 500 = 0 ThenLet Application.StatusBar = "Processing Row: " & Format(r, "#,##0")End If
Let v = rng.Cells(r, 1).Value
If v = vbNullString ThenIf Application.WorksheetFunction.CountIf(rng.Columns(1), vbNullString) > 1 Thenrng.Rows(r).EntireRow.DeleteLet n = n + 1End IfElseIf Application.WorksheetFunction.CountIf(rng.Columns(1), v) > 1 Thenrng.Rows(r).EntireRow.DeleteLet n = n + 1End IfEnd IfNext r
EndMacro:Let Application.StatusBar = FalseLet Application.ScreenUpdating = TrueLet Application.Calculation = xlCalculationAutomatic
MsgBox CStr(n) & "Linha(s) Duplicada(s) Deleta(s) "End Sub

Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...


Tags: VBA, Excel, Column, Coluna, Delete, Linha, Plan, Planilhas, Report, Row,  rows,worksheet, lines, duplicate, duplicado, dados, paste, cut


Excel Tips - Excluindo linhas em branco ao abrir a Planilha - Removing Blank Rows Automatically


Olá pessoal!

Alguns perguntaram como fazer para deletar as linhas que estão em branco na planilha, logo que a esta for aberta.

Segue um código, simples, honesto, rápido e limpinho.

Private Sub Worksheet_Change (ByVal Target As Range)
'Deleta todas as linhas que estiverem em branco que existirem.  
'Previne loops infinitos  Let Application.EnableEvents = False   
'Caso haja mais de uma célula selecionada. 
If Target.Cells.Count > 1 Then
GoTo SelectionCode  
If WorksheetFunction.CountA(Target.EntireRow) = 0 Then 
Target.EntireRow.Delete 
End If  
Let Application.EnableEvents = True  
Exit Sub
SelectionCode: 
If WorksheetFunction.CountA(Selection.EntireRow) = 0 Then 
Selection.EntireRow.Delete 
End If  
Let Application.EnableEvents = True
End Sub


Tags: VBA, Excel, deletar, apagar, excluir, row, lines, linha, range, rows, blank, removing, EntireRow, automatically, delete

diHITT - Notícias