Views

...

Important:

Quaisquer soluções e/ou desenvolvimento de aplicações pessoais, ou da empresa, que não constem neste Blog podem ser tratados como consultoria freelance.

E-mails

Deixe seu e-mail para receber atualizações...

eBook Promo

VBA Tips - Determina o tipo de conexão ativa - Determine Network Connection Type




A cada dia que passa é mais freqüente o uso de dados online oriundos de servidores na Web. Estes são automaticamente transformados em informações ao atualizarem os nossos Dashboards e Scorecards instantâneamente.

Para garantirmos que tais dados receberão as atualizações corretas no tempo apropriado é importante checarmos a conexão das nossas máquinas constantemente. A API InternetGetConnectedState declarada no wininet.dll retorna o estado da conexão do sistema local. A API é simples de usar, e retorna TRUE se houver uma conexão com a Internet.
As funções abaixo são muito úteis para garantir a validade de processos com este perfil:

IsNetConnectViaLAN

IsNetConnectViaModem

IsNetConnectViaProxy

IsNetConnectOnline

IsNetRASInstalled

GetNetConnectString


Inline image 2

Divirta-se com o código abaixo, colando-o inteiramente num novo módulo da sua aplicação.


Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/ Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce
'               or publish this code on any web site,
'               online service, or distribute as source
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Declare Function InternetGetConnectedState Lib "wininet" _
  (ByRef dwflags As Long, _
   ByVal dwReserved As Long) As Long

'Local system uses a modem to connect to the Internet.
Private Const INTERNET_CONNECTION_MODEM As Long = &H1

'Local system uses a LAN to connect to the Internet.
Private Const INTERNET_CONNECTION_LAN As Long = &H2

'Local system uses a proxy server to connect to the Internet.
Private Const INTERNET_CONNECTION_PROXY As Long = &H4

'No longer used.
Private Const INTERNET_CONNECTION_MODEM_BUSY As Long = &H8

Private Const INTERNET_RAS_INSTALLED As Long = &H10
Private Const INTERNET_CONNECTION_OFFLINE As Long = &H20
Private Const INTERNET_CONNECTION_CONFIGURED As Long = &H40

Private Sub Command1_Click()
   Let Text1.Text = IsNetConnectViaLAN()
   Let Text2.Text = IsNetConnectViaModem()
   Let Text3.Text = IsNetConnectViaProxy()
   Let Text4.Text = IsNetConnectOnline()
   Let Text5.Text = IsNetRASInstalled()
   Let Text6.Text = GetNetConnectString()
End Sub

Function IsNetConnectViaLAN() As Boolean
   Dim dwflags As Long
   
  'pass an empty variable into which the API will
  'return the flags associated with the connection
   Call InternetGetConnectedState(dwflags, 0&)

  'return True if the flags indicate a LAN connection
   IsNetConnectViaLAN = dwflags And INTERNET_CONNECTION_LAN
End Function

Function IsNetConnectViaModem() As Boolean
   Dim dwflags As Long
   
  'pass an empty variable into which the API will
  'return the flags associated with the connection
   Call InternetGetConnectedState(dwflags, 0&)

  'return True if the flags indicate a modem connection
   Let IsNetConnectViaModem = dwflags And INTERNET_CONNECTION_MODEM
End Function

Function IsNetConnectViaProxy() As Boolean

   Dim dwflags As Long
   
  'pass an empty variable into which the API will
  'return the flags associated with the connection
   Call InternetGetConnectedState(dwflags, 0&)

  'return True if the flags indicate a proxy connection
   Let IsNetConnectViaProxy = dwflags And INTERNET_CONNECTION_PROXY
End Function

Function IsNetConnectOnline() As Boolean
  'no flags needed here - the API returns True
  'if there is a connection of any type
   Let IsNetConnectOnline = InternetGetConnectedState(0&, 0&)
End Function

Function IsNetRASInstalled() As Boolean
   Dim dwflags As Long
   
  'pass an empty variable into which the API will
  'return the flags associated with the connection
   Call InternetGetConnectedState(dwflags, 0&)

  'return True if the flags include RAS installed
   Let IsNetRASInstalled = dwflags And INTERNET_RAS_INSTALLED
End Function

Function GetNetConnectString() As String

   Dim dwflags As Long
   Dim msg As String

  'build a string for display
   If InternetGetConnectedState(dwflags, 0&) Then
     
      If dwflags And INTERNET_CONNECTION_CONFIGURED Then
         Let msg = msg & "Você tem uma conexão de rede configurada." & vbCrLf
      End If

      If dwflags And INTERNET_CONNECTION_LAN Then
         Let msg = msg & "O sistemas local conecta-se a Internet via LAN"
      End If
      
      If dwflags And INTERNET_CONNECTION_PROXY Then
         Let msg = msg & ", e usuários no Servidor de Proxy. "
      Else
         Let msg = msg & "."
      End If
      
      If dwflags And INTERNET_CONNECTION_MODEM Then
         Let msg = msg & "O sistema local usa um modem para conectar-se a Internet. "
      End If
      
      If dwflags And INTERNET_CONNECTION_OFFLINE Then
         Let msg = msg & "A conexão está offline. "
      End If
      
      If dwflags And INTERNET_CONNECTION_MODEM_BUSY Then
         Let msg = msg & "O sistema de Modem local está ocupado com uma conexão non-Internet. "
      End If
      
      If dwflags And INTERNET_RAS_INSTALLED Then
         Let msg = msg & "Serviço de Acesso Remoto instalado neste sistema."
      End If
      
   Else
    
      Let msg = "Não conectado a Internet agora."
      
   End If
   
   Let GetNetConnectString = msg
End Function




Tags: VBA, Tips, Network, Connection, Type, code, network, DLL, wininet.dll

VBA Excel - Funções que retornam o Path e nome do Arquivo - Formula to Return the Full File Path & Name of Excel Workbooks

Estas funções retornarão o nome da planilha em uma célula, ou o caminho e o nome do arquivo na respectiva pasta de trabalho.

Function MyName() As String
Let MyName = ThisWorkbook.Name
End Function

Formula             Result
=MyName()         Workbook Path.xls




Function MyFullName() As String
Let MyFullName = ThisWorkbook.FullName 
End Function

Formula                Result
=MyFullName()       C:\Bernardess\Workbook Path.xls
=CELL("filename")*  C:\Bernardess\[Workbook Path.xls]Sheet1

*A função CELL é uma função padrão que retorna informação sobre o sistema operacional corrente. Para mais detalhes sobre ela veja o Help do MS Excel.

Function SheetName (rAnyCell)    
Application.Volatile    

Let SheetName = rAnyCell.Parent.Name 
End Function

Formula             Result
=sheetname(A1)  Sheet1


Tags: VBA, Excel, formula, workbook, Return, Full File Path, Name of Excel Workbooks, Excel Worksheet Name, Cell

VBA Excel - Listando todas as fórmulas de uma planilha - List All Formulas in Workbook

Às vezes temos planilhas tão complexas, tão cheias de fórmulas que chegam a ficar confusas para uma manutenção.

Inline image 2

Quando precisamos revisar essas planilhas com as suas fórmulas, talvez trocando algumas referências, e/ou fazendo leves ajustes, isso pode tornar-se um verdadeiro caos. Ou pode ser que queiramos apenas imprimir as respectivas planilhas com as fórmulas.

Inline image 3

Sim, seria muito mais fácil se simplesmente pudéssemos enxergar o conteúdo das células com as fórmulas e não com os valores que estas refletem. Mas como fazer isso? 

Que tal usar a programação para termos mais detalhes sobre como os cálculos funcionam,  e criarmos uma lista de todas as fórmulas em cada planilha? No código a seguir, uma nova planilha é criada para cada planilha que contém fórmulas. A nova planilha será nomeado  com o prefixo "F_" seguida do nome original.

Inline image 4

Coloque este código num módulo regular:

Sub ListAllFormulas()
'print the formulas in the active workbook
Dim lRow As Long
Dim wb As Workbook
Dim ws As Worksheet
Dim wsNew As Worksheet
Dim c As Range
Dim rngF As Range
Dim strNew As String
Dim strSh As String
On Error Resume Next
Application.DisplayAlerts = False

Set wb = ActiveWorkbook
strSh = "F_"

For Each ws In wb.Worksheets
  lRow = 2
  
  If Left(ws.Name, Len(strSh)) <> strSh Then
    Set rngF = Nothing
    On Error Resume Next
    Set rngF = ws.Cells.SpecialCells(xlCellTypeFormulas, 23)
    If Not rngF Is Nothing Then
      strNew = Left(strSh & ws.Name, 30)
      Worksheets(strNew).Delete
      Set wsNew = Worksheets.Add
      With wsNew
        .Name = strNew
        .Columns("A:E").NumberFormat = "@" 'text format
        .Range(.Cells(1, 1), .Cells(1, 5)).Value _
            = Array("ID", "Sheet", "Cell", "Formula", "Formula R1C1")
        For Each c In rngF
          .Range(.Cells(lRow, 1), .Cells(lRow, 5)).Value _
            = Array(lRow - 1, ws.Name, c.Address(0, 0), _
              c.Formula, c.FormulaR1C1)
          lRow = lRow + 1
        Next c
        .Rows(1).Font.Bold = True
        .Columns("A:E").EntireColumn.AutoFit
      End With 'wsNew
      Set wsNew = Nothing
    End If
  
  End If
Next ws
  
Application.DisplayAlerts = True
End Sub

Neste código as planilha de fórmulas são apagadas antes de criarmos uma nova. No entanto, se desejar excluí-las sem criar um novo conjunto, pode executar o seguinte código:

Sub ClearFormulaSheets()
' Remove formula sheets

Dim wb As Workbook
Dim ws As Worksheet
Dim strSh As String

On Error Resume Next

Let Application.DisplayAlerts = False

Set wb = ActiveWorkbook
strSh = "F_"

Set wb = ActiveWorkbook
  For Each ws In wb.Worksheets
    If Left(ws.Name, Len(strSh)) = strSh Then
      ws.Delete
    End If
  Next ws
  
Application.DisplayAlerts = True
End Sub


ReferenceDebra Dalgleish

Tags: VBA, Excel, formula, workbook

VBA Excel - Gravando histórico das alterações na planilha - Log in Sheet


Que tal acompanhar as alterações e intervenções efetuadas nos seus Relatórios, Dashboards e Scorecards desenvolvidos com o MS Excel?

Sim, com uma simples implementação, e algum código poderá acompanhar tudo o que foi alterado na sua planilha.

Este recurso pode ser útil:

Ao acompanharmos padrões de manipulação dos dados.

Para rastrearmos as ações de um determinado usuário.

Na detecção de erros.

Se você tiver algum tempo adicional, poderá implementar essa alteração em todas as planilhas corporativas ou nas que você disponibilizar, podendo concentrar o histórico de todas num único local.

Sim, é possível fazer tais registros em arquivo texto, ou mesmo numa base de dados MS Access

1 - Crie uma aba History
2 - Cole o código abaixo no módulo EstaPasta_de_trabalho (ThisWorkbook).

Sub Workbook_SheetChange (ByVal Sh As Object, ByVal Target As Range)

    ' Author:                     Date:               Contact:                 URL:
    ' André Bernardes             02/10/2012 10:58    bernardess@gmail.com     http://inanyplace.blogspot.com/
    ' documenta as alterações efetuadas nessa planilha.
    
    Dim wsHist As Worksheet, Rng As Range
    
    Set wsHist = Sheets("History")
    Let Application.ScreenUpdating = False
    Let Sheets("History").Visible = True
    
    If Sh Is wsHist Then Exit Sub

    Set Rng = wsHist.Range("A" & Rows.Count).End(xlUp).Offset(1)

    With Rng
        Let .Value = Now
        Let .Offset(, 1) = "Sheet: " & Sh.Name & " in Workbook: " & Replace(Sh.Application.Caption, "Microsoft Excel - ", "") & " no Path: " & Sh.Application.DefaultFilePath
        Let .Offset(, 2) = "Alterado por: " & Sh.Application.UserName
        Let .Offset(, 3) = Target.Address
        Let .Offset(, 4) = Target.Formula
    End With

    Let Application.ScreenUpdating = True
    Let Sheets("History").Visible = False
End Sub

3 - Salve a planilha e altere o conteúdo de uma célula.


Tags: VBA, Excel, Log, Sheet, Info, histórico, registro, histórico, alteração, planilha

eBooks VBA na AMAZOM.com.br

LinkWithinBrazilVBAExcelSpecialist

Related Posts Plugin for WordPress, Blogger...

Vitrine