About Me
Com tecnologia do Blogger.
Seguidores
Estatisticas
2006-04-06
Um dia destes, foi-me perguntado, por mail, qual a fórmula que permite contar as ocorrências de um caracter numa célula. Exemplo:
Quantos caracteres "." tem na célula A1 cujo conteúdo é 01.02.03.04? A célula A1 neste caso é do tipo texto. O resultado deveria ser 3.
Utilizando as Funções LEN() e SUBSTITUTE(), obtém-se o resultado desejado:

A fórmula em B1:
=LEN(A1)-LEN(SUBSTITUTE(A1;".";""))
(em Português):
=NÚM.CARACT(A1)-NÚM.CARACT(SUBSTITUIR(A1;".";""))
Quantos caracteres "." tem na célula A1 cujo conteúdo é 01.02.03.04? A célula A1 neste caso é do tipo texto. O resultado deveria ser 3.
Utilizando as Funções LEN() e SUBSTITUTE(), obtém-se o resultado desejado:
A fórmula em B1:
=LEN(A1)-LEN(SUBSTITUTE(A1;".";""))
(em Português):
=NÚM.CARACT(A1)-NÚM.CARACT(SUBSTITUIR(A1;".";""))
2006-03-19
Se pretendermos que uma determinada célula sequencie sempre que quisermos abrir um workbook, podemos utilizar o seguinte código de McGimpsey, com a adaptação no código de abertura do workbook, uma vez que se incluiu no número sequencial o ano, no formato "nn/aa", com a porção de código & "/" & Right(Date, 2)
O código da Função NextSeqNumber():
Public Function NextSeqNumber(Optional sFileName As String, Optional nSeqNumber As Long = -1) As Long
Const sDEFAULT_PATH As String = "C:\GABINETE"
Const sDEFAULT_FNAME As String = "defaultseq.txt"
Dim nFileNumber As Long
nFileNumber = FreeFile
If sFileName = "" Then sFileName = sDEFAULT_FNAME
If InStr(sFileName, Application.PathSeparator) = 0 Then _
sFileName = sDEFAULT_PATH & Application.PathSeparator & sFileName
If nSeqNumber = -1& Then
If Dir(sFileName) <> "" Then
Open sFileName For Input As nFileNumber
Input #nFileNumber, nSeqNumber
nSeqNumber = nSeqNumber + 1&
Close nFileNumber
Else
nSeqNumber = 1&
End If
End If
On Error GoTo PathError
Open sFileName For Output As nFileNumber
On Error GoTo 0
Print #nFileNumber, nSeqNumber
Close nFileNumber
NextSeqNumber = nSeqNumber
Exit Function
PathError:
NextSeqNumber = -1&
End Function
NOTA:
sDEFAULT_PATH e sDEFAULT_FNAME indicados a título de exemplo, podendo ser, como óbvio, alterados.
NOTA:
A célula onde recai o valor sequencial, deve ser formatada como texto.
O Código de abertura do Workbook:
Private Sub Workbook_Open()
ThisWorkbook.Sheets(1).Range("B2").Value = NextSeqNumber & "/" & Right(Date, 2)
End Sub
O resultado:

O código da Função NextSeqNumber():
Public Function NextSeqNumber(Optional sFileName As String, Optional nSeqNumber As Long = -1) As Long
Const sDEFAULT_PATH As String = "C:\GABINETE"
Const sDEFAULT_FNAME As String = "defaultseq.txt"
Dim nFileNumber As Long
nFileNumber = FreeFile
If sFileName = "" Then sFileName = sDEFAULT_FNAME
If InStr(sFileName, Application.PathSeparator) = 0 Then _
sFileName = sDEFAULT_PATH & Application.PathSeparator & sFileName
If nSeqNumber = -1& Then
If Dir(sFileName) <> "" Then
Open sFileName For Input As nFileNumber
Input #nFileNumber, nSeqNumber
nSeqNumber = nSeqNumber + 1&
Close nFileNumber
Else
nSeqNumber = 1&
End If
End If
On Error GoTo PathError
Open sFileName For Output As nFileNumber
On Error GoTo 0
Print #nFileNumber, nSeqNumber
Close nFileNumber
NextSeqNumber = nSeqNumber
Exit Function
PathError:
NextSeqNumber = -1&
End Function
NOTA:
sDEFAULT_PATH e sDEFAULT_FNAME indicados a título de exemplo, podendo ser, como óbvio, alterados.
NOTA:
A célula onde recai o valor sequencial, deve ser formatada como texto.
O Código de abertura do Workbook:
Private Sub Workbook_Open()
ThisWorkbook.Sheets(1).Range("B2").Value = NextSeqNumber & "/" & Right(Date, 2)
End Sub
O resultado:
2006-03-04
Por vezes, podemos ter a necessidade e utilizar, num Userform, um TextBox com comprimento fixo e com Multiline e WordWrap. Vejamos o exemplo:

Quando se inicia a escrita, a altura do TextBox aumenta automaticamente até à altura previamente definida:

Grava para a célula A1:

Para invocar o Userform que contem o TextBox, criamos um CommandButton na grelha:

O Código para o Comando:
Private Sub CommandButton1_Click()
FrmTeste.Show
End Sub
Os códigos em VBA:

Private Sub TextBox1_Change()
TextBox1.Width = 150
TextBox1.MultiLine = True
TextBox1.WordWrap = True
TextBox1.AutoSize = False
With Me.TextBox1
.Height = 80
End With
End Sub

Private Sub CommandButton1_Click()
Range("A1") = TextBox1.Value
End Sub
Quando se inicia a escrita, a altura do TextBox aumenta automaticamente até à altura previamente definida:
Grava para a célula A1:
Para invocar o Userform que contem o TextBox, criamos um CommandButton na grelha:
O Código para o Comando:
Private Sub CommandButton1_Click()
FrmTeste.Show
End Sub
Os códigos em VBA:
Private Sub TextBox1_Change()
TextBox1.Width = 150
TextBox1.MultiLine = True
TextBox1.WordWrap = True
TextBox1.AutoSize = False
With Me.TextBox1
.Height = 80
End With
End Sub
Private Sub CommandButton1_Click()
Range("A1") = TextBox1.Value
End Sub
2006-02-18
Num newsgroup foi colocada a seguinte questão: "Quando peço os sub-totais de uma folha, só fica em bold o campo da 1ª coluna. O que eu pretendo é que toda a linha do sub-total fique em bold automaticamente".
Para que os valores correspondentes aos subtotais fiquem automaticamente em BOLD, quando usamos subtotais para analisar uma lista, podemos utilizar a Formatação Condicional:
Vejamos o exemplo:

Utilizando a Função RIGHT() na Formatação Condicional:
Faz-se a selecção do Range e na Formatação Condicional, em Condição, escolhe-se "Formula Is" e digita-se a fórmula =RIGHT($A1;5)="Total", abre-se o campo Format e escolhe-se Bold:


O resultado:

Para que os valores correspondentes aos subtotais fiquem automaticamente em BOLD, quando usamos subtotais para analisar uma lista, podemos utilizar a Formatação Condicional:
Vejamos o exemplo:
Utilizando a Função RIGHT() na Formatação Condicional:
Faz-se a selecção do Range e na Formatação Condicional, em Condição, escolhe-se "Formula Is" e digita-se a fórmula =RIGHT($A1;5)="Total", abre-se o campo Format e escolhe-se Bold:
O resultado:
2006-02-11
Num newsgroup, foi feita a seguinte pergunta: Será que é possivel num Range em que tenho números (1,2,3,4,5, etc.) acrescentar letras atrás (COL1,COL2,COL3,COL4,COL5, etc.) sem editar célula a célula?
Selecciona-se o Range pretendido:

Executa-se a macro:

O resultado:

O Código do exemplo, em VBA:
Option Explicit
Sub AdicionaTexto()
Dim rng As Range
Dim rngCell As Range
Const sCHARACTER As String = "COL"
On Error GoTo Exit_AdicionaTexto
Set rng = ActiveWindow.RangeSelection
For Each rngCell In rng.Cells
If IsEmpty(rngCell.Value) = False Then
rngCell.Value = sCHARACTER & rngCell.Value
End If
Next rngCell
Exit_AdicionaTexto:
Set rngCell = Nothing
Set rng = Nothing
End Sub
Selecciona-se o Range pretendido:
Executa-se a macro:
O resultado:
O Código do exemplo, em VBA:
Option Explicit
Sub AdicionaTexto()
Dim rng As Range
Dim rngCell As Range
Const sCHARACTER As String = "COL"
On Error GoTo Exit_AdicionaTexto
Set rng = ActiveWindow.RangeSelection
For Each rngCell In rng.Cells
If IsEmpty(rngCell.Value) = False Then
rngCell.Value = sCHARACTER & rngCell.Value
End If
Next rngCell
Exit_AdicionaTexto:
Set rngCell = Nothing
Set rng = Nothing
End Sub
2006-02-06
Se pretendermos efectuar um cálculo para obter a diferença entre dois horários e sabermos o resultado em minutos, podemos utilizar, por exemplo, os seguintes métodos:



E se a hora final for inferior à hora inicial, como no caso de a hora final ser já depois da meia-noite? Aqui, podemos utilizar a seguinte fórmula:
E se a hora final for inferior à hora inicial, como no caso de a hora final ser já depois da meia-noite? Aqui, podemos utilizar a seguinte fórmula:
2006-01-22
O MVP em Excel,Kirill Lapin, também conhecido por KL, apresentou uma alternativa ao post anterior, que pela sua qualidade e simplicidade, passo a referir:
O Código:
Private Sub CommandButton2_Click()
Dim r As Long
For r = UsedRange.Rows.Count To 1 Step -1
If Range("A" & r) = "" And Range("H" & r) = "" Then _
Range("A:H").Rows(r).Interior.ColorIndex = 48
Next r
End Sub
O Código:
Private Sub CommandButton2_Click()
Dim r As Long
For r = UsedRange.Rows.Count To 1 Step -1
If Range("A" & r) = "" And Range("H" & r) = "" Then _
Range("A:H").Rows(r).Interior.ColorIndex = 48
Next r
End Sub
2006-01-14
Se tivermos um determinado Range de dados como no exemplo que se segue:

e quisermos colorir as linhas totalmente em branco desse Range:

Podemos utilizar um pouco de VBA.
O Código:
Private Sub CommandButton2_Click()
Dim RowNdx As Long
Dim LastRow As Long
Dim x
Dim y
LastRow = ActiveSheet.UsedRange.Rows.Count
For RowNdx = LastRow To 1 Step -1
On Error Resume Next
x = Cells(RowNdx, "A").Value = ""
y = Cells(RowNdx, "H").Value = ""
If x Then
If y Then
Cells(RowNdx, "A").Interior.ColorIndex = 48
Cells(RowNdx, "B").Interior.ColorIndex = 48
Cells(RowNdx, "C").Interior.ColorIndex = 48
Cells(RowNdx, "D").Interior.ColorIndex = 48
Cells(RowNdx, "E").Interior.ColorIndex = 48
Cells(RowNdx, "F").Interior.ColorIndex = 48
Cells(RowNdx, "G").Interior.ColorIndex = 48
Cells(RowNdx, "H").Interior.ColorIndex = 48
End If
End If
Next RowNdx
End Sub
e quisermos colorir as linhas totalmente em branco desse Range:
Podemos utilizar um pouco de VBA.
O Código:
Private Sub CommandButton2_Click()
Dim RowNdx As Long
Dim LastRow As Long
Dim x
Dim y
LastRow = ActiveSheet.UsedRange.Rows.Count
For RowNdx = LastRow To 1 Step -1
On Error Resume Next
x = Cells(RowNdx, "A").Value = ""
y = Cells(RowNdx, "H").Value = ""
If x Then
If y Then
Cells(RowNdx, "A").Interior.ColorIndex = 48
Cells(RowNdx, "B").Interior.ColorIndex = 48
Cells(RowNdx, "C").Interior.ColorIndex = 48
Cells(RowNdx, "D").Interior.ColorIndex = 48
Cells(RowNdx, "E").Interior.ColorIndex = 48
Cells(RowNdx, "F").Interior.ColorIndex = 48
Cells(RowNdx, "G").Interior.ColorIndex = 48
Cells(RowNdx, "H").Interior.ColorIndex = 48
End If
End If
Next RowNdx
End Sub
2006-01-09
Por vezes podemos ter a necessidade de redefinir uma tecla para uma outra. No exemplo seguinte, redefine-se a tecla ENTER (incluindo a numérica) para a tecla TAB e provoca-se um avanço de uma coluna na mesma linha:
Sub Auto_open()
Application.OnKey "~", "JumpNext"
Application.OnKey "{ENTER}", "JumpNext1"
End Sub
Sub JumpNext()
r = ActiveCell.Row
c = ActiveCell.Column
If c >= 1 Then
c = c + 1
r = r
Else
End If
Cells(r, c).Activate
End Sub
Sub JumpNext1()
r = ActiveCell.Row
c = ActiveCell.Column
If c >= 1 Then
c = c + 1
r = r
Else
End If
Cells(r, c).Activate
End Sub
Sub Auto_open()
Application.OnKey "~", "JumpNext"
Application.OnKey "{ENTER}", "JumpNext1"
End Sub
Sub JumpNext()
r = ActiveCell.Row
c = ActiveCell.Column
If c >= 1 Then
c = c + 1
r = r
Else
End If
Cells(r, c).Activate
End Sub
Sub JumpNext1()
r = ActiveCell.Row
c = ActiveCell.Column
If c >= 1 Then
c = c + 1
r = r
Else
End If
Cells(r, c).Activate
End Sub
2006-01-03
Se tivermos preenchidas linhas, como no exemplo

e pretendermos inserir linhas em branco após 4 linhas de dados, ou seja, sempre à próxima 5ª linha,

podemos utilizar o seguinte Código, adaptado de Dave Peterson:
Private Sub CommandButton1_Click()
'Adiciona 1 linha em branco após 4 linhas
'Código original por: Dave Peterson
Dim iCtr As Long
Dim LastRow As Long
Dim myRng As Range
With ActiveSheet
LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
Set myRng = Nothing
For iCtr = 5 To LastRow Step 4
If myRng Is Nothing Then
Set myRng = .Cells(iCtr, "A")
Else
Set myRng = Union(.Cells(iCtr, "A"), myRng)
End If
Next iCtr
End With
If myRng Is Nothing Then
'Não faz nada
Else
myRng.EntireRow.Insert
End If
End Sub
e pretendermos inserir linhas em branco após 4 linhas de dados, ou seja, sempre à próxima 5ª linha,
podemos utilizar o seguinte Código, adaptado de Dave Peterson:
Private Sub CommandButton1_Click()
'Adiciona 1 linha em branco após 4 linhas
'Código original por: Dave Peterson
Dim iCtr As Long
Dim LastRow As Long
Dim myRng As Range
With ActiveSheet
LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
Set myRng = Nothing
For iCtr = 5 To LastRow Step 4
If myRng Is Nothing Then
Set myRng = .Cells(iCtr, "A")
Else
Set myRng = Union(.Cells(iCtr, "A"), myRng)
End If
Next iCtr
End With
If myRng Is Nothing Then
'Não faz nada
Else
myRng.EntireRow.Insert
End If
End Sub
Subscrever:
Mensagens (Atom)