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

MS Excel - Deletando múltiplas linhas em branco - 02.



Ampliando o tema:

A primeira executa o Loop decrescente o que é útil quando há muitas linhas vazias em sequência

Dim i As Integer

With Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
For i = Cells(Rows.Count,3).End(xlUp).Row To 11 Step -1
If Isempty(Cells(i,3)) Then Rows(i).Delete
Next i

.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
End With
End Sub

Esta 2ª versão não utiliza Loop sendo útil para arquivos que não sejam muito pesados.

Sub DeletLinhasVazias()
Range("C11:C" & Cells(Rows.Count, 3).End(xlUp).Row).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub


Tags: Excel, Column, Coluna, Delete, Linha, Plan, Planilhas, Report, Row,  rows,worksheet, lines



André Luiz Bernardes
A&A® - In Any Place.

Excel VBA: 30 Livros como sugestão.

A leitura é indispensável, tudo o que sabemos, recebemos de alguém e é muito bom compararmos o modo como estamos solucionando os nossos problemas com o modo como outros têm solucionado os seus. É especialmente enriquecedor poder comparar soluções diferentes para o mesmo problema, o que acontece quando comparamos diferentes autores.

Os títulos que citei são em inglês somente por um motivo, geralmente compro os livros em inglês. Por quê? Por outro motivo também simples: Os títulos, o software, as dicas, os treinamentos, os vídeos todos saem primeiro em inglês e depois, em alguns casos bem depois, é que as versões traduzidas são disponibilizadas no mercado.

A leitura destes geralmente não requer nenhuma grande erudição no idioma inglês, muita coisa é simples e o restante intuitivo. Quem programa em uma ou mais linguagens sabe do que estou falando.

Minha sugestão? Aventure-se!

Seguem-se os primeiros 30 Livros:

: : A Fast Track To Structured Finance Modeling, Monitoring and Valuation: Jump Start VBA by William Preinitz
: : Advanced modelling in finance using Excel and VBA by Mary Jackson and Mike Staunton
: : Computing with Excel and VBA: A Problem Solving Approach, Second Edition by S. I. Krishan
: : Credit Risk Modeling using Excel and VBA (The Wiley Finance Series) by Gunter Loeffler and Peter N. Posch
: : Definitive Guide to Excel VBA, Second Edition by Michael Kofler
: : Excel 2007 Formulas (Mr. Spreadsheet's Bookshelf) by John Walkenbach
: : EXCEL 2007 MACROS MADE EASY by Gail Perry
: : Excel 2007 Power Programming with VBA (Mr. Spreadsheet's Bookshelf) by John Walkenbach
: : Excel 2007 VBA Programmer's Reference (Programmer to Programmer) by John Green, Stephen Bullen, Rob Bovey, and Michael Alexander
: : Excel Scientific and Engineering Cookbook (Cookbooks (O'Reilly)) by David Bourg
: : Excel VBA and Macros with MrExcel (Video Training) (LiveLessons) by Bill Jelen
: : Excel VBA in Easy Steps by Ed Robinson
: : Excel VBA Macro Programming by Richard Shepherd
: : Holy Macro! It's 2,500 Excel VBA Examples: Every Snippet of Excel VBA Code You'll Ever Need by Hans Herber, Bill Jelen, and Tom Urtis
: : Learn Excel from Mr. Excel: 277 Excel Mysteries Solved by Bill Jelen
: : Master Excel 2003 and 2007 VBA Programming Basics - Harmonial Staff
: : Mastering VBA by Guy Hart-Davis
: : Mastering VBA for Microsoft Office 2007 by Richard Mansfield
: : Microsoft Excel VBA Programming for the Absolute Beginner, 3E by Duane Birnbaum and Michael Vine
: : Microsoft® Office Excel® 2007 Visual Basic® for Applications Step by Step (BPG-step by Step) by Reed Jacobson
: : Option Pricing Models and Volatility Using Excel-VBA (Wiley Finance) by Fabrice Douglas Rouah and Gregory Vainberg
: : Power Programming with VBA/Excel (ESource Series) by Steven C. Chapra
: : Pro Excel 2007 VBA (Expert's Voice in Excel VBA) by Jim DeMarco
: : Pro Excel 2007 VBA by Jim DeMarco (Kindle Edition - Feb 28, 2008) - Kindle Book
: : Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft(R) Excel and VBA(R) (Addison-Wesley Microsoft Technology Series) by Stephen Bullen, Rob Bovey, and John Green
: : VB and VBA in a Nutshell: The Languages by Paul Lomax
: : VBA and Macros for Microsoft Office Excel 2007 (Business Solutions) by Bill Jelen and Tracy Syrstad
: : VBA for Modelers: Developing Decision Support Systems Using Microsoft® Excel - by S. Christian Albright
: : Writing Excel Macros with VBA, 2nd Edition by Steven Roman

Excel VBA: Abrindo caixa de diálogo

Segue código pronto para o COPIAR e COLAR.

Abra a caixa de diálogo e escolha o arquivo que desejar no propósito que preferir.

Dim strFilePath As String, strPath As String
Dim fdgO As FileDialog, varSel As Variant

MsgBox "A tabela não está correta, " &
_
"e o arquivo de dados não pôde ser achado na respectiva pasta: " & _
strPath & ". Por favor,localize a pasta que contenha dados de exemplo " & _
".: Dialog.", vbInformation, gstrAppTitle

Set fdgO = Application.FileDialog(msoFileDialogFilePicker)
With fdgO

.AllowMultiSelect = False

.Title = "Localize a pasta com dados de exemplo"

.ButtonName = "Escolha"

.Filters.Clear

.Filters.Add "All Files", "*.*", 1

.FilterIndex = 1

.InitialFileName = strPath

.InitialView = msoFileDialogViewDetails

If .Show = 0 Then
MsgBox "Houve falha para selecionar o arquivo correto. ATENÇÃO: " & _
"Você talvez não tenha aberto uma tabela conectada a aplicação. " & _
" Você pode re-abrir este formulário ou " & _
"inicie o formulário, tentando novamente.", vbCritical,
gstrAppTitle

Let CheckConnect = False

Exit Function
End If

Let strFilePath = .SelectedItems(1)
End With

Let strPath = Left(strFilePath, InStrRev(strFilePath, "\") - 1)
Let varSel = AttachAgain(strPath)



André Luiz Bernardes

VBA Excel - Conectando planilhas com tabelas do MS Access.

Inline image 1

Segue parte de um código que pode usar para conectar todas as planilhas do MS Excel que estiverem disponíveis no mesmo diretório, a uma base de dados MS Access.

Este código assume que os cabeçalhos estão na primeira linha da planilha. Divirta-se!

Sub LinkXls()
     ' Loop num diretório específico (nPath)
     ' linkando todos os arquivos MS Excel como tabelas no MS Access.
     
    Const nPath As String = "C:\tmp\XLs\" 'Diretório.
    Dim nArq As String           ' Nomes dos arquivos.
    Dim nFile() As String           ' Array com os arquivos.
    Dim intFile As Integer          ' Número de arquivos.
    Dim IniLine As String           ' Limita Range.
    Dim FinLine As String           '       "
    Dim IniColumn As String         '       "
    Dim FinColumn As String         '       "
    Dim nFrase As String            ' Frase de definição.

    'Loop na pasta e construção da lista de arquivos.
    Let nArq = Dir(nPath & "*.xls")
    
    While nArq <> ""
        'Adicionando arquivos à lista.
        Let intFile = intFile + 1
        
        ReDim Preserve nFile(1 To intFile)
        
        Let nFile(intFile) = nArq
        Let nArq = Dir()
    Wend
    
    ' Verifica se achou o arquivo.
    If intFile = 0 Then
        MsgBox "Nenhum arquivo encontrado!", vbCritical, ".: A&A"
        Exit Sub
    End If
    
    ' Define tamanho do range a ser conectado, considerando a primeira linha como título.
    ' IniLine    - Linha inicial.
    ' FinLine    - Linha final.
    ' IniColumn  - Coluna inicial.
    ' FinColumn  - Coluna final.
    
    'Linhas.
    Let IniLine = 1
    Let FinLine = 50
    
    ' Colunas
    Let IniColumn = "A"
    Let FinColumn = "J"
    
    Let nFrase = IniLine & IniColumn & FinLine & FinColumn

    ' Inicia o ciclo de conexções na base de dados MS Access.
    For intFile = 1 To UBound(nFile)
        DoCmd.TransferSpreadsheet acLink, , nFile(intFile), nPath & nFile (intFile), True, nFrase
    Next
    
    MsgBox UBound(nFile) & " Arquivos 'Linkados'", vbInformation, ".: A&A"
End Sub

Tags: Excel, Access, udf, import, data, conect, directory, TransferSpreadSheet

Inline image 2

André Luiz Bernardes
bernardess@gmail.com


VBA Access & Excel: Carregando dados em um FORM no Excel, a partir de dados disponíveis no Access

VBA Access & Excel: Carregando dados em um FORM no Excel, a partir de dados disponíveis no Access



Function ReadcbDisciplina()

    ' Author:                           Date:                     Contact:
    ' André Bernardes             22/07/2008 11:35    bernardess@gmail.com
    ' Carrega dados no Combo "cbDisciplina".


    On Error GoTo ErrorHandler              ' Ative a rotina de tratamento de erro.

    ' Define Vars.
    Dim cnt As ADODB.Connection
    Dim rst As ADODB.Recordset

    Dim k As Long
    Dim stDB As String
    Dim stSQL As String
    Dim vaData As Variant

    ' Efetua a conexão.
    Set cnt = New ADODB.Connection                                                  ' Inicia a conexão do objeto (Instantiate the Connection object).
    Let stDB = dbTarget                                                             ' Path to and the name of the database. Assumes the DB and worksheet are in same directory. If not, you need to specify DB path

    ' Limpa o Combo.
    Me.cbDisciplina.Clear

    ' Constrói a consulta SQL.
    Let stSQL = stSQL & "SELECT DISTINCT tbl_data_Disciplinass.Sigla, tbl_data_Disciplinass.Disciplina" & Space(1)
    Let stSQL = stSQL & "FROM tbl_data_Disciplinass" & Space(1)
    Let stSQL = stSQL & "WHERE (((tbl_data_Disciplinass.Active) = -1))" & Space(1)
    Let stSQL = stSQL & "ORDER BY tbl_data_Disciplinass.Disciplina"

    With cnt
        .CursorLocation = adUseClient       ' Necesary for creating disconnected recordset.
        .Open stConn                        ' Open connection.

        Set rst = .Execute(stSQL)           ' Instantiate the Recordsetobject and execute the SQL-statement.
    End With

    With rst
        Set .ActiveConnection = Nothing     ' Disconnect the recordset.
        Let k = .Fields.Count

        vaData = .GetRows                   ' Populate the array with the whole recordset.
    End With

    cnt.Close                               ' Close the connection.

    'Really manipulate the Combobox's properties and show the data.
    With Me
        With .cbDisciplina
            .Clear
            .BoundColumn = k
            .AddItem
            .Column = vaData                ' ? vaData(0,0),vaData(1,0),vaData(2,0) - (? vaData(coluna,linha),vaData(coluna,linha),vaData(coluna,linha))
            .ListIndex = -1
        End With
    End With

    Let FirstLoad = True
    Set rst = Nothing                       ' Tira os objetos da memória (Release objects from memory).
    Set cnt = Nothing

ErrorHandler:                           ' Rotina de tratamento de erro.
    Call ErrorShow(Err.Number, Err.Description, Err.Source)
End Function



 Clique aqui e nos contate via What's App para avaliarmos seus projetos 

Envie seus comentários e sugestões e compartilhe este artigo!
brazilsalesforceeffectiveness@gmail.com


 Série de Livros nut Project 

DONUT PROJECT: VBA - Projetos e Códigos de Visual Basic for Applications (Visual Basic For Apllication)eBook - DONUT PROJECT 2024 - Volume 03 - Funções Financeiras - André Luiz Bernardes eBook - DONUT PROJECT 2024 - Volume 02 - Conectando Banco de Dados - André Luiz Bernardes eBook - DONUT PROJECT 2024 - Volume 01 - André Luiz Bernardes


 PUDIM PROJECT 

eBook - PT - PUDIM PROJECT 2024 - Python Volume 01 - Funções Essenciais - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 02 - Funções Essenciais - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 03 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes


eBook - PT - PUDIM PROJECT 2024 - Python Volume 04 - Funções para Automatização - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 05 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 06 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes


eBook - PT - PUDIM PROJECT 2024 - Python Volume 07 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 08 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 09 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes


eBook - PT - PUDIM PROJECT 2024 - Python Volume 10 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes eBook - PT - PUDIM PROJECT 2024 - Python Volume 11 - Automatizando Postagens em Redes e Plataformas Sociais - Série PUDIM PROJECT — André Luiz Bernardes

diHITT - Notícias