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

VBA Excel - Deletando todas as procedures da planilha - Delete all macros in a workbook









Simplemente passe o rodo na sua planilha!

Antes de continuar, um pequeno parênteses, deixe seus comentários para este post. 

Sub DeleteProcedureCode (ByVal wb As Workbook, _
                                            ByVal DeleteFromModuleName As String, 
                                            ByVal ProcedureName As String)

' deletes ProcedureName from DeleteFromModuleName in wb
Dim VBCM As CodeModule, ProcStartLine As Long, ProcLineCount As Long

    On Error Resume Next

    Set VBCM = wb.VBProject.VBComponents(DeleteFromModuleName).CodeModule

    If Not VBCM Is Nothing Then
        ' determine if the procedure exist in the codemodule
        Let ProcStartLine = 0
        Let ProcStartLine = VBCM.ProcStartLine(ProcedureName, vbext_pk_Proc)

        If ProcStartLine > 0 Then ' prosedyren finnes, slett den
            Let ProcLineCount = VBCM.ProcCountLines(ProcedureName, vbext_pk_Proc)
            VBCM.DeleteLines ProcStartLine, ProcLineCount
        End If

        Set VBCM = Nothing
    End If

    On Error GoTo 0
End Sub



Reference:

Tags:  VBA, Excel, content, module, módulo, Class Modules in VBA, delete, del, excluir, apagar, procedure, function  


VBA Excel - Deletando uma procedure de um módulo - Delete a procedure from a module

Esse código permite que você apague somente uma procedure dentro de um módulo. Alteração cirúrgica!

Antes de continuar, um pequeno parênteses, deixe seus comentários para este post. 

DeleteProcedureCode Workbooks ("wb_Bernardes.xlsb"), "mdl_Functions", "ExtractData"

Sub DeleteProcedureCode (ByVal wb As Workbook, _
                                           ByVal DeleteFromModuleName As String, _
                                           ByVal ProcedureName As String)

' deletes ProcedureName from DeleteFromModuleName in wb
Dim VBCM As CodeModule, ProcStartLine As Long, ProcLineCount As Long

On Error Resume Next

    Set VBCM = wb.VBProject.VBComponents(DeleteFromModuleName).CodeModule

    If Not VBCM Is Nothing Then
        ' determine if the procedure exist in the codemodule
        Let ProcStartLine = 0
        Let ProcStartLine = VBCM.ProcStartLine(ProcedureName, vbext_pk_Proc)

        If ProcStartLine > 0 Then ' prosedyren finnes, slett den
            Let ProcLineCount = VBCM.ProcCountLines(ProcedureName, vbext_pk_Proc)

            VBCM.DeleteLines ProcStartLine, ProcLineCount
        End If

        Set VBCM = Nothing
    End If

    On Error GoTo 0
End Sub

Reference:

Tags: VBA, Excel, content, module, módulo, Class Modules in VBA, delete, del, excluir, apagar, procedure, function 


VBA excel - Deletando um módulo - Delete a module using VBA in Microsoft Excel







Esse código aparentemente não tem uma grande importância, mas se souber usá-lo, poderá torná-lo parte da sua coletânea de artifícios para proteger seus projetos e aplicações.

Antes de continuar, um pequeno parênteses, deixe seus comentários para este post. 

Ao apagar um módulo, todas as funcionalidade da planilha dependentes desse módulo ficam automaticamente inativas. Que dica hein! 

Segue o código: DelVBComponent ActiveWorkbook, "mdl_MainFunctions"

Sub DelVBComponent (ByVal wb As Workbook, ByVal CompName As String)
' deletes the vbcomponent named CompName from wb

    Let Application.DisplayAlerts = False

    On Error Resume Next ' ignores any errors

    wb.VBProject.VBComponents.Remove wb.VBProject.VBComponents (CompName) 

    ' delete the component
    On Error GoTo 0

    Let Application.DisplayAlerts = True
End Sub



Reference:

Tags:  VBA, Excel, content, module, módulo, Class Modules in VBA, delete, del, excluir, apagar,     



VBA Excel - Copiando o módulo entre os workbooks - Copy modules from one workbook to another

Inline image 1

Em algumas planilhas, em especial aquelas onde temos uns 4 ou 5 Dashboards, existem funções de navegação e mesmo layouts que são adaptáveis ao seu respectivo conteúdo (contexto). Em muitas delas o comportamento é similar, mas não exatamente igual. Podemos até tornar as funcionalidades customizáveis de acordo com a opção escolhida para análise. Com essa técnica podemos como que estender os 'poderes'  da planilha durante a análise feita nela. Isso é que é polimorfismo! O Mesmo objeto, mas com novas características nos eventos.

Antes de continuar, um pequeno parênteses, deixe seus comentários para este post. 

Bem, introdução à parte, o código abaixo permite que migre todo o conteúdo de um workbook para outro. Siga a sintaxe:CopyModule Workbooks ("Bernardes_Plan01.xlsb"), "mdl_Navigation_Functions", Workbooks ("Bernardes_Plan0.xlsb")

Sub CopyModule (SourceWB As Workbook, strModuleName As String, _
                            TargetWB As Workbook)

    Dim strFolder As String, strTempFile As String

    Let strFolder = SourceWB.Path

    If Len(strFolder) = 0 Then Let strFolder = CurDir

    Let strFolder = strFolder & "\"
    Let strTempFile = strFolder & "~tmpexport.bas"
    
    On Error Resume Next

    SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
    TargetWB.VBProject.VBComponents.Import strTempFile
    
    Kill strTempFile
    
    On Error GoTo 0
End Sub



Reference:

Tags: VBA, Excel, content, add, module, módulo, copy, copiar, Module, conteúdo, Modules, Class Modules in VBA, kill, export, workbook  


VBA Excel - Adicionando um conteúdo para um módulo a partir de um arquivo - Add content to a module from a file using VBA in Microsoft Excel









Ao efetuar a manutenção de uma aplicação talvez não desejemos importar todo um módulo, mas apenas algumas funcionalidades ou processos deste.

Antes de continuar, um pequeno parênteses, deixe seus comentários para este post. 

Selecionamos então as funcionalidades que desejamos e as colamos em um arquivo texto externo. Com o código abaixo somos capazes de importar o arquivo externo, inserindo o código dele no módulos que selecionarmos: ImportModuleCode ActiveWorkbook, "mdl_ExternalCode", "C:\Bernardes\nCodes.txt"


Sub ImportModuleCode (ByVal wb As Workbook, _
                                       ByVal ModuleName As String, _
                                       ByVal ImportFromFile As String)

' imports code to ModuleName in wb from a textfile named ImportFromFile
Dim VBCM As CodeModule

    If Dir(ImportFromFile) = "" Then Exit Sub
    On Error Resume Next

    Set VBCM = wb.VBProject.VBComponents(ModuleName).CodeModule

    If Not VBCM Is Nothing Then
        VBCM.AddFromFile ImportFromFile
        Set VBCM = Nothing
    End If

    On Error GoTo 0
End Sub


Reference:

Tags:VBA, Excel, content, add, module, módulo, adicionar, Module, conteúdo, Modules, Class Modules in VBA, 

VBA Excel - Adicionando uma Procedure a um módulo - Add a procedure to a module using

Inline image 1

Podemos inserir Funções ou Subs em módulos pré-existentes na nossa planilha. Para isso basta que programemos o seguinte código em qualquer evento da nossa planilha:

Antes de continuar, um pequeno parênteses, deixe seus comentários para este post. 

InsertProcedureCode Workbooks("WorkBookBernardes.xlsb"), "mdl_Functions_AutomaticInserted"

Sub InsertProcedureCode (ByVal wb As Workbook, ByVal InsertToModuleName As String)
Dim VBCM As CodeModule
Dim InsertLineIndex As Long

    On Error Resume Next

    Set VBCM = wb.VBProject.VBComponents(InsertToModuleName).CodeModule

    If Not VBCM Is Nothing Then

        With VBCM
            Let InsertLineIndex = .CountOfLines + 1

            ' customize the next lines depending on the code you want to insert
            .InsertLines InsertLineIndex, "Sub NewSubName()" & Chr(13)
           
             Let InsertLineIndex = InsertLineIndex + 1
            .InsertLines InsertLineIndex, _
                "    Msgbox ""Olá Mundo!"",vbInformation,"".: Primeira""" & Chr(13)

            Let InsertLineIndex = InsertLineIndex + 1

            .InsertLines InsertLineIndex, "End Sub" & Chr(13)
            ' no need for more customizing
        End With

        Set VBCM = Nothing

    End If

    On Error GoTo 0
End Sub


Reference:
Tags:  VBA, Excel, procedure, add, module, módulo, adicionar, Modules, Class Modules in VBA


VBA Excel - Criando um novo módulo automaticamente - Create a new module

Inline image 1

Inserir um novo módulo de maneira automática numa planilha talvez seja um processo que possa automatizar na estação de trabalho onde começa a desenvolver as suas novas aplicações com o MS Excel. Essa característica, sem dúvida, o ajudaria a tornar o seu ponto de partida mais ágil.

Como?

Bem, use o código abaixo e divirta-se!

CreateNewModule ActiveWorkbook, 1, "TestModule"

Sub CreateNewModule (ByVal wb As Workbook, _
                                      ByVal ModuleTypeIndex As Integer, _
                                      ByVal NewModuleName As String)

' creates a new module of ModuleTypeIndex 
' (1=standard module, 2=userform, 3=class module) in wb
' renames the new module to NewModuleName (if possible)

Dim VBC As VBComponent, mti As Integer
    Set VBC = Nothing
    Let mti = 0

    Select Case ModuleTypeIndex
        Case 1: mti = vbext_ct_StdModule ' standard module
        Case 2: mti = vbext_ct_MSForm ' userform
        Case 3: mti = vbext_ct_ClassModule ' class module
    End Select

    If mti <> 0 Then
        On Error Resume Next

        Set VBC = wb.VBProject.VBComponents.Add(mti)

        If Not VBC Is Nothing Then
            If NewModuleName <> "" Then
                Let VBC.Name = NewModuleName
            End If
        End If

        On Error GoTo 0

        Set VBC = Nothing
    End If
End Sub




Reference:
Tags:  VBA, Excel, content, module, módulo, Class Modules in VBA, create


VBA Tips - Deletando um Módulo após rodar o código nele - Delete Module After Running VBA Code

Inline image 1

Este código abaixo pode ser utilizada para eliminar um módulo que abriga um código. Em outras palavras, ele se apaga depois de executado uma vez.
Sub DeleteThisModule()
    Dim vbCom As Object
    MsgBox "Olá, estou deletando a mim mesmo. "
    Set vbCom = Application.VBE.ActiveVBProject.VBComponents
    vbCom.Remove VBComponent:= vbCom.Item("Module1")
End Sub

Reference: 

Tags: VBA, Excel, module, delete, code


Inline image 1

VBA Tips - 101 Exemplos de código no Office 2010 - 101 Samples for Office 2010 Development

VBA Tips - 101 Exemplos de código no Office 2010 - 101 Samples for Office 2010 Development




O Microsoft Office 2010 tem as ferramentas necessárias para criar aplicativos poderosos. As aplicações abaixo, desenvolvidas com o Visual Basic for Applications (VBA), são amostras de códigos que podem ajudá-lo a criar seus próprios aplicativos que executam funções específicas ou servirem como ponto de partida para criar soluções mais complexas.


Cada amostra de código a seguir é composta de aproximadamente 5 a 50 linhas de código. Cada amostra inclui comentários descrevendo o código para que possa executá-los com os resultados esperados e os comentários explicarão como configurar o ambiente para que o código de exemplo seja executado.

Baixe todos os códigos em um único arquivo zip, ou clique em cada título individual para baixar o código VBA: 

Office 2010 101 Code Samples.zipExemplos de Código - MS Office 2010 101.zip
Excel 2010
Excel 2010: Add Icon Sets for Ranges Using Excel.AddIconSetCondition
Excel 2010: Apply Conditional Formatting Using the Excel.DataBar Method
Excel 2010: Change Colors to Indicate Values Above and Below Average in Ranges
Excel 2010: Communicate with PageSetup Using the Excel.PrintCommunication Method
Excel 2010: Create and Manipulate Custom Views Using Excel.CustomView Method
Excel 2010: Create Charts Events Programmatically
Excel 2010: Determine Open Add-Ins Using Excel.TestAddIn.IsOpen
Excel 2010: Display Top Ten Percent in Ranges Programmatically
Excel 2010: Display Unique Numbers in Ranges Using Excel.AddUnique
Excel 2010: Enable Removal of Duplicate Rows Using Excel.RemoveDuplicates
Excel 2010: Export Data to PDF or XPS Using the Excel.ExportAsFixedFormat Method
Excel 2010: Format Data Ranges Using the Excel.DisplayFormat Method
Excel 2010: Formatting Colors in Ranges Using Excel.AddColorScale
Excel 2010: Manipulate UI Properties Using Excel.ApplicationProperties
Excel 2010: Modify Display Properties of Tables Using Excel.ListObjectDisplay
Excel 2010: Remove Various Properties Using Excel.RemoveDocumentInformation
Excel 2010: Retrieve Information About Chart Points Using Excel.PointClass
Excel 2010: Show Properties of Chart Series Using Excel.SeriesProperties
Excel 2010: Show Properties of Exceeded Frames Using Excel.TextFrameProperties
Excel 2010: Show Properties of ListObject Using Excel.ListObjectTableStyles
Excel 2010: Show Properties of the Window Object Using Excel.WindowProperties
Excel 2010: Sort and Filter Programmatically Using Excel.ListObjectSortFilter
Excel 2010: Sort Data Programmatically Using Excel.WorksheetSort
Excel 2010: Use Properties of Sparkline Groups Using Excel.SparkLines
Excel 2010: Work with DataBodyRange and Total Properties Using Excel.ListColumn
Excel 2010: Work with Gradient Fill Features Using Excel.Gradient Method
Excel 2010: Work with Header and Footer Properties Using Excel.PagesAndPage
Excel 2010: Work with Hyperlinks Programmatically
Excel 2010: Work with Several Date Functions Using Excel.WorksheetFunctionDates

Excel 2010: Work with Various Properties Using Excel.PageSetup Object

Office 2010
Office 2010: Change Chart Layouts Using Office.Chart.ModifyChartLayout
Office 2010: Create Bar Charts Using Office.Chart.CreateSimpleChart
Office 2010: Modify Chart Axis Text Using Office.Chart.WorkWithAxisText
Office 2010: Modify Chart Legends Using Office.Chart.WorkWithLegend
Office 2010: Modify Chart Titles Using Office.Chart.WorkWithTitle


OneNote 2010
OneNote 2010: Create New Pages Programmatically Using OneNote.CreateOneNotePage
OneNote 2010: Manipulate Docking Using OneNote.fromVBA.DockWindow
OneNote 2010: Navigate to Objects in OneNote 2010 Using OneNote.NavigateTo
OneNote 2010: Open, Close, and Display OneNote 2010 Notebooks in a New Window
OneNote 2010: Output OneNote 2010 Page Content from VBA Sources
OneNote 2010: Output OneNote 2010 Page Content to PDF Files
OneNote 2010: Perform Keyword Searches in OneNote and Get Results in XML Format
OneNote 2010: Retrieve Attribute Data About Sections in OneNote 2010 Notebooks
OneNote 2010: Retrieve Data About Notebooks Using OneNote.fromVBA.ListNotebooks
OneNote 2010: Retrieve Information About Open OneNote 2010 Windows
OneNote 2010: Retrieve Metadata From Pages of OneNote 2010 Notebook Sections
OneNote 2010: Return Backup Folder Data Locations Using GetSpecialLocation


Outlook 2010
Outlook 2010: Access Lists of SharePoint Objects Using Outlook.PickerDialog
Outlook 2010: Create SMS and MMS Messages Using Outlook.MobileItem
Outlook 2010: Manipulate Items in Mail Conversations Using Outlook.Conversations


PowerPoint 2010
PowerPoint 2010: Add and Format Shapes Using PPT.ColorFormat.Brightness
PowerPoint 2010: Add Series of Application-Level Events Using PPT.NewEvents
PowerPoint 2010: Apply Themes & Backgrounds Using PPT.ApplyTheme.BackgroundStyle
PowerPoint 2010: Change Chart Locations Using PPT.InteractWithChartLocation
PowerPoint 2010: Control Animation Click Behavior Using PPT.SlideShowClicks
PowerPoint 2010: Convert Text into SmartArt Using PPT.ConvertTextToSmartArt
PowerPoint 2010: Copy Animation Using PPT.PickupAndApplyAnimation
PowerPoint 2010: Create Videos Programmatically
PowerPoint 2010: Display Media Control Properties
PowerPoint 2010: Export Slides as PPTX Files Using PPT.PublishSlides
PowerPoint 2010: Insert, Move, Get Section Counts Using PPT.WorkWithSections
PowerPoint 2010: Interact with Table Styles Using PPT.Table.ApplyStyle
PowerPoint 2010: Link Videos and Embedded Audio Files Using PPT.AddMedia
PowerPoint 2010: List SmartArt Names Using PPT.WorkWithSmartArt
PowerPoint 2010: Merge Two Decks into One Using PPT.MergeWithBaseline
PowerPoint 2010: Modify Aspects of Videos Using PPT.MediaFormatProperties
PowerPoint 2010: Resample and Reset Resolution Using PPT.ResampleMedia
PowerPoint 2010: Set Background Fill in Tables Using PPT.TableBackground
PowerPoint 2010: Set Banding and Scaling of Tables Using PPT.TableProperties
PowerPoint 2010: Use Custom XML Data Using PPT.CustomerDataDemo
PowerPoint 2010: View Properties of ShadowFormat Class Using PPT.Shadow
PowerPoint 2010: Work with FillFormat Texture Settings Using PPT.ShapeTexture
PowerPoint 2010: Work with Methods of Player Class Using PPT.WorkWithMediaPlayer


Visio 2010
Visio 2010: Add Containers and Connect Shapes in Visio 2010 Documents
Visio 2010: Add Containers to Visio Documents Using Visio.ContainerProperties
Visio 2010: Bind Two Shapes Together Using Visio.Page.DropCallout
Visio 2010: Manipulate Connected Shapes Using Visio.Page.DropConnected
Visio 2010: Manipulate Raster Export Resolution Settings
Visio 2010: Manipulate Shape Properties Using Visio.DropContainer
Visio 2010: Read and Write Raster Export Resolution Settings

Word 2010
Word 2010: Add Application-Level Events Using Word.New Application Events
Word 2010: Add Glow and Reflection Effects to Text
Word 2010: Add Picture Shapes and Format Cropping Using Word.PictureFormat.Crop
Word 2010: Apply a Quick Style Set Using Word.QuickStyleSets
Word 2010: Apply Themes and Styles Using Word.DocumentApplyThemeQuickStyle
Word 2010: Check-In Word 2010 Documents with Versioning on SharePoint Servers
Word 2010: Clear Formatting Using Word.SelectionClearFormatting
Word 2010: Compare Features of Two Documents Using Word.DemoCompareDocuments
Word 2010: Create a New Quick Style Set Using Word.SaveAsQuickStyleSet
Word 2010: Export and Import Text Fragments Using Word.RangeImportExportFragment
Word 2010: Ignore Punctuation, Match Prefixes and Suffixes, Clear Highlighting
Word 2010: List Combo Box Content Information Using Word.ContentControlLists
Word 2010: Make and Save Edits Concurrently Using Word.Coauthoring
Word 2010: Manipulate Check Box Controls Using Word.CheckBoxContentControl
Word 2010: Rotate and Warp Text Using Word.WorkWithTextFrame
Word 2010: Work with Auto-Hyphenation Using Word.ConvertAutoHyphens
Word 2010: Work with Nested Undo Records Using Word.NestedCustomUndoRecords
Word 2010: Work with Properties of Range Object Using Word.CharParagraphStyle
Word 2010: Work with the Undo Stack Using Word.CustomUndoRecord


Referências: MSDN


Tags: VBA, Office, Office 2010, MSDN, MSDN Library, Microsoft, solutions, tools, applications, developer, Microsoft Office 2010, technology


diHITT - Notícias