Word VBA – Imprimindo a lista de nomes dos comandos das barras de ferramentas

Querendo saber mais informações sobre as barras de ferramentas do Word? A Microsoft ajuda. Neste exemplo de código, o VBA imprime em um novo documento todos os nomes, rótulos e FaceId de todas as barras de ferramentas existentes.

O exemplo foi apresentado pelo Paulo Cesar Semblano do fórum Julio Battisti.

Do site da Microsoft:
Gerar uma lista de nomes da barra de comandos, legendas e os números de ID:

Sub FindFaceIDsWordDocument()

'This code prints the information to a new Word document.

Dim c As CommandBar, ctl As CommandBarControl

Application.Documents.Add

For Each c In Application.CommandBars
For Each ctl In c.Controls
If ctl.Type = msoControlButton Then
Selection.TypeText "CommandBar Name: " & c.Name & _
" | Caption: " & ctl.Caption & " | Face Id : " & ctl.FaceId
Selection.TypeParagraph
End If
Next
Next

End Sub

Outros sites da Microsoft:
http://support.microsoft.com/kb/213209/pt
http://support.microsoft.com/kb/213552/pt

Abraços

Tomás Vásquez
www.tomasvasquez.com.br

Excel 2000 – Habilitando o AutoFiltro em uma planilha protegida

Ativar o AutoFiltro em uma planilha protegida desde o Excel XP/2002 é uma tarefa simples, já que ao protegê-la, a caixa de diálogo oferecida já oferece esta possibilidade.

O problema é que os usuários do Excel 2000, que ainda são muitos não gozam desta funcionalidade. Felizmente, a Microsoft publicou um código em VBA que implementa esta funcionalidade. O código abaixo efetua a proeza:

1
2
3
4
5
6
Private Sub Workbook_Open()
    Sheet1.Protect password:="test", DrawingObjects:=True, _
        contents:=True, Scenarios:=True, _
        userinterfaceonly:=True
    Sheet1.EnableAutoFilter = True
End Sub

Resumidamente, o código efetua a proteção tradicionalmente e habilita o autofiltro logo em seguida.

A referência e código completo podem ser vistos neste link:

http://office.microsoft.com/en-us/excel/HA010982701033.aspx

Abraços

Tomás Vásquez
www.tomasvasquez.com.br

Excel VBA – Escrevendo números por extenso

Usando-se o Excel / VBA seria possível escrever-se uma função que após ler um numero na forma tradicional, o converta para forma “por extenso” ? Essa função em outras palavras, deverá ser capaz de ler um valor qualquer inteiro e escreve-lo por extenso (ex:”Quatro Mil Duzentos e Quinze”). Isso é possível ? Ficamos gratos pelo Help.

Public Function EscrevePorExtenso(ByVal n As Double) As String
    Unid = Array("", "Um", "Dois", "Três", "Quatro", "Cinco", _
                 "Seis", "Sete", "Oito", "Nove", "Dez", "Onze", "Doze", _
                 "Treze", "Quatorze", "Quinze", "Dezesseis", "Dezessete", _
                 "Dezoito", "Dezenove", "Vinte")
    Dezen = Array("", "Dez", "Vinte", "Trinta", "Quarenta", _
                  "Cinquenta", "Sessenta", "Setenta", "Oitenta", "Noventa")
    Centen = Array("", "Cento", "Duzentos", "Trezentos", _
                   "Quatrocentos", "Quinhentos", "Seiscentos", _
                   "Setecentos", "Oitocentos", "Novecentos", "Mil")
    Num = n
    Escr = ""
    If n = 0 Then
        Escr = "Zero"
    End If
    If (n \ 1000) > 0 And n \ 1000 < 10 Then         Escr = Unid(n \ 1000) & " Mil "     End If     n = n - (n \ 1000) * 1000     If n > 100 Then
        Escr = Escr & Centen(n \ 100)
    End If
    If n = 100 Then
        Escr = Escr & " Cem"
        GoTo Prossiga
    End If
    n = n - (n \ 100) * 100
    If n >= 20 And n < 100 Then         Escr = Escr & " " & Dezen(n \ 10)     End If     If n > 0 And n < 20 Then         Escr = Escr & " " & Unid(n)         GoTo Prossiga     End If     n = n - (n \ 10) * 10     If n > 0 Then
        Escr = Escr & " " & Unid(n)
    End If
Prossiga:
    If Num Mod 10 <> 0 Then
        If InStr(1, Escr, "Vinte", 1) = 0 Then
            If InStr(1, Escr, "Trinta", 1) = 0 Then
                If InStr(1, Escr, "enta", 1) > 0 Then
                    Escr = Application.Substitute(Escr, "enta", "enta e ")
                End If
            End If
        End If
    End If
    If Num Mod 10 <> 0 Then
        If InStr(1, Escr, "Vinte", 1) > 0 Then
            If InStr(1, Escr, "Trinta", 1) = 0 Then
                If InStr(1, Escr, "enta", 1) = 0 Then
                    Escr = Application.Substitute(Escr, "Vinte", "Vinte e ")
                End If
            End If
        End If
    End If
    If Num Mod 10 <> 0 Then
        If InStr(1, Escr, "Vinte", 1) = 0 Then
            If InStr(1, Escr, "Trinta", 1) > 0 Then
                If InStr(1, Escr, "enta", 1) = 0 Then
                    Escr = Application.Substitute(Escr, "Trinta", "Trinta e ")
                End If
            End If
        End If
    End If
    If Num Mod 100 <> 0 Then
        If InStr(1, Escr, "ento", 1) > 0 Then
            Escr = Application.Substitute(Escr, "Cento", "Cento e ")
        End If
    End If
    If Num Mod 100 <> 0 Then
        If InStr(1, Escr, "entos", 1) > 0 Then
            Escr = Application.Substitute(Escr, "entos", "entos e ")
        End If
    End If
    If Num Mod 1000 <> 0 Then
        If (Num - (Num \ 1000) * 1000) <= 100 Then             If InStr(1, Escr, "Mil", 1) > 0 Then
                Escr = Application.Substitute(Escr, "Mil", "Mil e ")
            End If
        End If
    End If
End Function

A função suporta números até 9999. Não é muito, mas já quebra um galho.

Bom proveito!

Fonte: BestExcel

Tomás Vásquez
www.tomasvasquez.com.br

Excel VBA – Delete rows based on criteria

It’s impressive how often this question has been made on the forum (www.tomavasquez.com.br/forum).

I’ve saw many solutions posted, each one different from another. Those were not bad solutions, but they didn’t solve all conditions.

Well, I decided to take the best of it togheter in one piece of generic code and the result is the macro below:

Function DeleteRowsByCriteria(ByVal firstRow As Integer, ByVal lastRow As Integer, ByVal criteriaColumn As Integer, ByVal criteria As String) As Integer
    Dim deletedRows As Integer
    Dim i As Integer
    deletedRows = 0
    With ActiveSheet
        i = firstRow
        While i < lastRow
            If CStr(.Cells(i, criteriaColumn).Value) = criteria Then
                .Rows(i).Delete
                deletedRows = deletedRows + 1
            Else
                i = i + 1
            End If
        Wend
    End With
    DeleteRowsByCriteria = deletedRows
End Function

Parameters

  • firstRow – the index of the first row of the Range to be evaluate
  • lastRow – the index of the last row of the Range to be evaluate
  • criteriaColumn – the index of the column in the Range to be evaluate
  • criteria – the criteria value

With these parameters, the loops over all rows in the range (based on firstRow and lastRow parameters), for each row, it evaluate the cell column (based on criteriaColumn parameter) and compare this value with the value in criteria parameter. If the comparison matches, the line will be deleted. As a final result, the function returns the quantity of rows deleted on the list.

Below you can check an example of how use the macro above:

Sub Execute()
    MsgBox DeleteRowsByCriteria (1, 200, 6, "London") & " rows has been deleted"
End Sub

On the code above, all rows in the current worksheet between line 1 and 200, wich have the value “London” in the colunm 6 or “F” will be deleted.

Be careful with this code. It does not ask for confirmation or data validation either. Configure it very carefully before run it.

Enjoy the code!