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

VBA Excel - Função DIR - 03 - Verificando a existência de um Arquivo - Check if a Files Exists



No VBA do Microsoft Excel, a função Dir é usada para retornar o primeiro nome do arquivo num diretório especificado, e uma lista dos seus atributos.

O nome do arquivo é retornado como uma String. A função Dir pode ser usada sem os respectivos argumentos para retornar o nome do próximo arquivo, neste mesmo diretório.

O uso mais comum da função Dir é percorrer todos os arquivos de uma pasta, executando uma ação em cada um. Outros usos comuns incluem a verificação da existência destes, saber se um diretório existe, ou procurar um arquivo específico.


Verificando a existência de um Arquivo

Sub FileExists()

      Dim TheFolder As string 'Location of the file
      Dim FiletoCheck As String 'Name of the file you want to check

TheFolder = "C:\ExcelFiles" 'Assign directory to TheFolder variable

'Capture the name of file to check for using an input box
FiletoCheck = InputBox("Enter the name of the file you want to look for", "Enter file name")

'If FiletoCheck is an empty string then file not found
If FiletoCheck = "" Then
     
      Msgbox "Oh no, the file does not exist"

Else

      Msgbox "Yes, the file exists."

End If

End Sub



Tags: Excel, VBA, Files, Folder, list, Dir, filedatetime, xls, xlsm, xlsb, arquivos, pasta, check, exists, function, directory, 

Inline image 1

VBA Excel - Copiando uma Tabela ou List para uma nova planilha - Copying a Table or List to a New Worksheet in the Current Workbook

Inline image 1

O procedimento a seguir copia apenas as células visíveis em uma tabela ou lista para uma nova planilha. O MS Excel tem um limite de 8.192 áreas não contíguas que pode ser copiado em qualquer tabela. 
Este código pergunta-lhe se você deseja criar uma tabela com os novos dados na nova planilha.
Sub CopyListOrTable2NewWorksheet()
'Works in Excel 2003 and Excel 2007. Only copies visible data.
    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

    'Check to see if the worksheet or workbook is protected.
    If ActiveWorkbook.ProtectStructure = True Or ActiveSheet.ProtectContents = True Then
        MsgBox "This macro will not work when the workbook or worksheet is write-protected."
        Exit Sub
    End If

    'Set a reference to the ActiveCell. You can always use ACell 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
    'do not 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
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
        End With

        'Test if there are more than 8192 separate areas. Excel only supports
        'a maximum of 8,192 non-contiguous areas through VBA macros and manual.
        On Error Resume Next
        With ACell.ListObject.ListColumns(1).Range
            CCount = .SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
        End With
        On Error GoTo 0

        If CCount = 0 Then
            MsgBox "There are more than 8192 areas, so it is not possible to " & _
                   "copy the visible data to a new worksheet. Tip: Sort your " & _
                   "data before you apply the filter and try this macro again.", _
                   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.
            sheetName = InputBox("What is the name of the new worksheet?", _
                                 "Name the New Sheet")

            On Error Resume Next
            New_Ws.Name = sheetName
            If Err.Number > 0 Then
                MsgBox "Change the name of sheet : " & New_Ws.Name & _
                     " manually after the macro is ready. The sheet name" & _
                     " you typed in already exists or you use characters" & _
                     " that are not allowed in a sheet name."
                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
                Application.CutCopyMode = False
            End With

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

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

            Application.ScreenUpdating = False

            'If you do not create a table, you have the option to copy the formats.
            If ActiveCellInTable = False Then
                Application.GoTo ACell
                CopyFormats = MsgBox("Do you also want to copy the Formats?", _
                                     vbOKCancel + vbExclamation, "Copy to new worksheet")
                If CopyFormats = vbOK Then
                    ACell.ListObject.Range.Copy
                    With New_Ws.Range("A1")
                        .PasteSpecial xlPasteFormats
                        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
            .ScreenUpdating = True
            .EnableEvents = True
        End With

    Else
        MsgBox "Select a cell in your list or table before you run the macro.", _
               vbOKOnly, "Copy to new worksheet"
    End If
End Sub

Reference

Tags: VBA, Excel, cell, check, table, list


Inline image 1

VBA Excel - Checando se a célula faz parte de uma Tabela ou Lista - Checking to See Whether the Active Cell is in a Table or List

Inline image 1

Muitas vezes, antes de executar outros comandos e funções, queremos garantir que a célula ativa esteja (ou não) em uma tabela ou lista. O código a seguir testa esta condição e exibe uma caixa de mensagem com os resultados.
Sub TestIfActiveCellIsInTable()
    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

    ActiveCellInTable = (ACell.ListObject.Name <> "")

    On Error GoTo 0

    If ActiveCellInTable = True Then
        MsgBox "The ActiveCell is a part of a table."
    Else
        MsgBox "The ActiveCell is not a part of a table."
    End If
End Sub

Reference

Tags: VBA, Excel, cell, check, table, list


Inline image 1

VBA Word: Checando número de revisões ao abrir

header_employer.jpg

Vida de escritor não é fácil, precisa-se de 'n' revisões até se chegar ao resultado final, seja ele um texto simples ou mesmo um livro (na verdade nada muito diferente do que fazemos em progração, 'n' revisões).

Bem, com respeito ao MS Office Word poderá acompanhar as 'n' versões logo que abrir o seu documento, por utilizar o código abaixo.

Divirta-se...

Dim rev As Revision

Debug.Print ActiveDocument.Revisions.Count

For Each rev In ActiveDocument.Revisions
      Debug.Print rev.Index
      Debug.Print rev.Type
      Debug.Print rev.Author
      Debug.Print rev.Date
      Debug.Print rev.Range.Text
Next


TagsWord, version, versão, check, revision, revisão

André Luiz Bernardes
A&A® - Work smart, not hard.


diHITT - Notícias