Às vezes eu preciso copiar texto e/ou valores de sites que geralmente vêm no formato html para colar no Excel, para tanto eu uso Colar > Especial > Valores.
Um jeito mais prático, é colar diretamente na barra de fórmulas, que acaba tendo o mesmo efeito, porém com menos click's.
Experimentem!
;-)
Eventualmente dicas sobre outros programas, Windows e hardware.
domingo, 7 de março de 2010
sábado, 6 de março de 2010
Exportar conta de e-mail no Outlook 2003
Ao transferir meus arquivos para um novo HD, com o XP recém-instalado, deparei com um problema inesperado: exportar a conta de e-mail no Outlook origem para depois importá-la no novo WinXP.
Aparentemente uma tarefa simples, mas... não existe a opção de exportar a conta!
O Outlook Express que é a versão simplificada do leitor de e-mail tem esse recurso, não entendo porque a Microsoft não incluiu no "irmão mais velho".
Bem, pesquisando pela internet, encontrei a solução através de uma chave no registro.
Segue o caminho das pedras.
Depois de localizar a chave, basta exportá-la e importar no outro PC.
Artigo original em http://www.infonegocio.com/luzylar/cuentasoutlook2003.htm
A "maledeta":
HKEY_CURRENT_USER\
Software\
Microsoft\
Windows NT\
CurrentVersion\
Windows Messaging Subsystem\
\Profiles\
Outlook\
9375CFF0413111d3B88A00104B2A6676
;-)
Aparentemente uma tarefa simples, mas... não existe a opção de exportar a conta!
O Outlook Express que é a versão simplificada do leitor de e-mail tem esse recurso, não entendo porque a Microsoft não incluiu no "irmão mais velho".
Bem, pesquisando pela internet, encontrei a solução através de uma chave no registro.
Segue o caminho das pedras.
Depois de localizar a chave, basta exportá-la e importar no outro PC.
Artigo original em http://www.infonegocio.com/luzylar/cuentasoutlook2003.htm
A "maledeta":
HKEY_CURRENT_USER\
Software\
Microsoft\
Windows NT\
CurrentVersion\
Windows Messaging Subsystem\
\Profiles\
Outlook\
9375CFF0413111d3B88A00104B2A6676
;-)
segunda-feira, 15 de fevereiro de 2010
Alinhar texto dentro de uma string
Olá!
Segue uma dica para alinhar um texto dentro de uma variável do tipo string.
Não vejo muita utilidade, pois quando temos possíveis espaços dentro de uma string e queremos trabalhar somente com o valor, faz mais sentido usar um TRIM(variável).
Bem, se a função existe, em alguma situação ela deve ter sua utilidade.
;-)
Segue uma dica para alinhar um texto dentro de uma variável do tipo string.
Não vejo muita utilidade, pois quando temos possíveis espaços dentro de uma string e queremos trabalhar somente com o valor, faz mais sentido usar um TRIM(variável).
Bem, se a função existe, em alguma situação ela deve ter sua utilidade.
;-)
Option Explicit
Dim texto As String
Sub teste()
texto = " azul "
Debug.Print texto
'Texto alinhado à esquerda dentro da variável
LSet texto = "azul"
Debug.Print texto
'Texto alinhado à direita dentro da variável
RSet texto = "azul"
Debug.Print texto
End Sub
domingo, 14 de fevereiro de 2010
Acessando dados do SQL Server Express 2005
ADO é um recurso muito versátil, permite ao Excel acessar base de dados como o Access, arquivos texto e também do SQL Server.
Vou mostrar aqui um exemplo bem simples de como acessar a tabela de clientes ("Customers") do Northwind.
Para quem quiser utilizar o recurso, não esqueça de marcar o "Microsoft Active Data Objects" nas referências do projeto VBA, pode ser qualquer versão. Aqui eu utilizei a 2.8.
;-)
Vou mostrar aqui um exemplo bem simples de como acessar a tabela de clientes ("Customers") do Northwind.
Para quem quiser utilizar o recurso, não esqueça de marcar o "Microsoft Active Data Objects" nas referências do projeto VBA, pode ser qualquer versão. Aqui eu utilizei a 2.8.
;-)
Option Explicit
Sub SQL_Express()
Dim rst As New ADODB.Recordset
Dim cnn As New ADODB.Connection
Dim i As Integer
cnn.Open "Provider=SQLNCLI;Data Source=(local)\SQLEXPRESS;uid=sa;pwd=123;database=northwind"
rst.CursorLocation = adUseClient
rst.Open "SELECT CompanyName FROM customers", cnn, adOpenKeyset, adLockOptimistic
i = 1
Do While Not rst.EOF
Cells(i, 1).Value = rst!CompanyName
i = i + 1
rst.MoveNext
Loop
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End Sub
sábado, 13 de fevereiro de 2010
Várias versões do Office no mesmo computador
Ter várias versões do Office sempre gera algum tipo de problema.
Lembro que tive a versão 97 com 2000, 97 com XP e recentemente 2003 com 2007.
Cansei de tantos pequenos problemas que resolvi ficar somente com o 2003 instalado, mais do que suficiente para as minhas necessidades.
Para quem quiser se aventurar... segue um link com dicas muito interessantes:
http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=762
;-)
Lembro que tive a versão 97 com 2000, 97 com XP e recentemente 2003 com 2007.
Cansei de tantos pequenos problemas que resolvi ficar somente com o 2003 instalado, mais do que suficiente para as minhas necessidades.
Para quem quiser se aventurar... segue um link com dicas muito interessantes:
http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=762
;-)
quarta-feira, 27 de janeiro de 2010
Usando a barra de status do Excel
Muitas vezes durante a execução de uma macro, queremos acompanhar o andamento do processo.Para isso, basta usar o recurso da barra de status do próprio Excel.
Abaixo um exemplo bem simples com um looping preenchendo um conjunto de células.
Ao lado, o resultado.
;-)
Option Explicit
Dim i As Integer
Sub status_bar()
For i = 1 To 5000
DoEvents
Cells(i, 1).Value = "Teste"
Application.StatusBar = "Preenchendo célula " & i & " de 5.000"
Next
Application.StatusBar = False
End Sub
domingo, 27 de dezembro de 2009
Office 2008 no Mac não tem VBA!
Muito estranho...
Bem, não sou usuário dos Mac's, talvez alguém que o seja possa contribuir com sua opinião.
Segue o link (tomara que não sumam com o artigo).
Vou guardar uma cópia em pdf no meu e-mail, caso o link esteja quebrado.
;-)
Verificar se uma planilha existe numa pasta fechada via VBA
Às vezes me deparo com pedidos estranhos em grupos de discussões e fóruns da vida.
;-)
Acabei de ver agora, um colega que precisa ver se uma planilha existe numa pasta que está fechada.
Tempos atrás eu precisei usar a linguagem SQL no VBA para inserir dados numa outra planilha, cuja pasta poderia ou não estar aberta. Para contornar isso, usei o ADO.
Importante: não esquecer de marcar a referência "Microsoft Active Data Objects" (versão de 2.6 para cima).
Aproveitando para relembrar conceitos... uma "pasta" do Excel contém planilhas (é muito comum as pessoas chamarem pastas de planilhas e confundirem pasta do Excel com pasta do Windows que são coisas bem diferentes!).
Tempos atrás eu precisei usar a linguagem SQL no VBA para inserir dados numa outra planilha, cuja pasta poderia ou não estar aberta. Para contornar isso, usei o ADO.
Importante: não esquecer de marcar a referência "Microsoft Active Data Objects" (versão de 2.6 para cima).
Aproveitando para relembrar conceitos... uma "pasta" do Excel contém planilhas (é muito comum as pessoas chamarem pastas de planilhas e confundirem pasta do Excel com pasta do Windows que são coisas bem diferentes!).
;-)
Sub ver()
Dim arquivo As String
arquivo = "c:\teste.xls"
Dim cnn As New ADODB.Connection
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;data source = " _
& arquivo & ";Extended Properties=Excel 8.0;"
On Error Resume Next
cnn.Execute "SELECT top 1 * from [planilha1$]"
If Err.Number = 0 Then
MsgBox "Planilha existe"
Else
MsgBox "Planilha não existe"
End If
cnn.Close
Set cnn = Nothing
End Sub
sexta-feira, 25 de dezembro de 2009
Corretor da nova ortografia no Word 2007
Demorou mas saiu:
http://www.microsoft.com/downloads/details.aspx?FamilyId=DF0AF8D5-A8DA-4938-8A44-E8BE7C8EEAEF&displaylang=pt-br
Ou na minha pasta compartilhada do 4shared, link mais acima da página.
;-)
http://www.microsoft.com/downloads/details.aspx?FamilyId=DF0AF8D5-A8DA-4938-8A44-E8BE7C8EEAEF&displaylang=pt-br
Ou na minha pasta compartilhada do 4shared, link mais acima da página.
;-)
domingo, 20 de dezembro de 2009
ListView no Access
Esta vou deixar aqui para futuras consultas.
Utilizo-o porque num ListBox não tem como alinhar números à direita.
Estranhamente num dos códigos, às vezes a primeira coluna é a zero (0) e em outras é 1.
Bem, se alguém souber como resolver os dois problemas (alinhar números à direita no ListBox e a questão da primeira coluna no ListView), me manda um e-mail.
Utilizo-o porque num ListBox não tem como alinhar números à direita.
Estranhamente num dos códigos, às vezes a primeira coluna é a zero (0) e em outras é 1.
Bem, se alguém souber como resolver os dois problemas (alinhar números à direita no ListBox e a questão da primeira coluna no ListView), me manda um e-mail.
Sub carrega_listview2()
With Me.Listview2
.View = lvwReport
.GridLines = True
.FullRowSelect = True
.ListItems.Clear
.ColumnHeaders.Clear
End With
'Cabeçalho do ListView
With Me.Listview2.ColumnHeaders
.Add , , "N/Número", 1500, lvwcolumright
.Add , , "Cartório", 1300, lvwColumnLeft
.Add , , "Protocolo", 1300, lvwcolumright
.Add , , "Vencimento", 1300, lvwColumnLeft
.Add , , "Valor", 1000, lvwcolumright
End With
'Adicionar itens
rst.MoveFirst
Do Until rst.EOF
Set lstItem = Me.Listview2.ListItems.Add()
lstItem.Text = Format(rst!Nosso_Numero, "000000000000000")
lstItem.SubItems(1) = Format(rst!numero_tabe_protesto, "00")
lstItem.SubItems(2) = Format(rst!numero_protocolo, "0000000000")
lstItem.SubItems(3) = rst!data_venc
lstItem.SubItems(4) = Format(rst!vl_titulo / 100, "#0.00")
rst.MoveNext
Loop
rst.Close
End Sub
quarta-feira, 25 de novembro de 2009
Excel 2010
Está chegando a hora...
Para quem quiser se aventurar, já está disponível a versão beta para download:
http://www.microsoft.com/office/2010/en/download-office-professional-plus/default.aspx
;-)
Para quem quiser se aventurar, já está disponível a versão beta para download:
http://www.microsoft.com/office/2010/en/download-office-professional-plus/default.aspx
;-)
domingo, 18 de outubro de 2009
Input box do Excel
Após um "longo e tenebroso inverno...", novamente as postagens de dicas de Excel.
Continuando no VBA, um InputBox muito mais prático do que o tradicional do VB/VBA.
Segue um exemplo e a imagem correspondente.
Option Explicit
Sub teste_box()
Dim variavel As Range
Set variavel = Application.InputBox(prompt:="Região a ser apagada:", _
Title:="Box do Excel", Type:=8)
variavel.ClearContents
End Sub
:-)
sábado, 29 de agosto de 2009
Descobrindo qual o nome da tabela vinculada no Access
Esta dica devo ao meu colega Cleiton que descobriu em 5 minutos o que eu gastei umas 2 horas pesquisando na internet...
A situação:
Se você vincula uma tabela de outro mdb e altera o nome do vínculo, a princípio parece que não se sabe qual o nome original da tabela, visto que o Access mostra o novo nome e apenas uma seta indicando que trata-se de uma tabela vinculada.
Abrindo as propriedades da tabela na janela do banco de dados, não aparece nenhuma informação, porém se abrirmos a estrutura da tabela e a partir daí, as propriedades, enfim o nome original da tabela é exibido.
Só mostrando a imagem para entender!
:-)
domingo, 10 de maio de 2009
E-mail pelo Excel - II
Continuo achando que é mais fácil fazer o código no próprio Outlook, mas muitos usuários ainda querem enviar e-mails através de outros aplicativos.
Possível é, mas são tantos os problemas de automação que não vejo o porque de tanta insistência em fazer o código no Excel e/ou outros aplicativos, haja vista que, quem usa o Office, quase sempre está com o Outlook aberto.
É a velha história do InputBox com máscara de senha: basta criar a tela com caixa de texto e alterar a máscara para "*****". Para que inventar códigos mirabolantes para fazer o InputBox receber senha? Ele não foi projetado para isso!
Bem, num dos grupos de Excel que participo recebi esta interessante mensagem sobre como mandar e-mails pelo Excel.
O problema que gerou a discussão, é a mensagem de confirmação que o Outlook exibe quando outro aplicativo tenta enviar e-mails através ele: "confirma (s/n)?".
Não testei o código e nem vou testar, apenas vou deixar registrado aqui para quem quiser se aventurar.
Ah, lembrando também que existe um programa chamado "ClickYes" para quem ainda tem o problema da mensagem de confirmação do Outlook.
abs!
original em: http://www.rondebruin.nl/cdo.htm
Sending mail from Excel with CDO
Ron de Bruin (last update 31-Oct-2007)
Go back to the mail tips page
What is CDO doing
The example code is using CDOSYS (CDO for Windows 2000).
It does not depend on MAPI or CDO and hence is dialog free
and does not use your mail program to send email.
Briefly to explain, this code builds the message and drops it
in the pickup directory, and SMTP service running on the machine
picks it up and send it out to the internet.
Why using CDO code instead of Outlook automation or SendMail in VBA.
1: It doesn't matter what Mail program you are using (It only use the SMTP server).
2: It doesn't matter what Office version you are using (97…2007)
3: You can send a range/sheet in the body of the mail (some mail programs can’t do this)
4: You can send any file you like (Word, PDF, PowerPoint, TXT files,….)
5: No Security warnings anymore, really great if you are sending a lot of mail in a loop.
Read this!!!
This code will not work in Win 98 and ME.
You must be connected to the internet when you run a example.
It is possible that you get a Send error when you use one of the examples.
AFAIK : This will happen if you haven't setup an account in Outlook Express or Windows Mail.
In that case the system doesn't know the name of your SMTP server.
If this happens you can use the commented green lines in each example.
Don't forget to fill in the SMTP server name in each code sample where
it says "Fill in your SMTP server here"
When you also get the Authentication Required Error you can add this three lines.
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "username"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
Don't remove the TextBody line in the code. If you do you can't open the attachment (bug in CDO).
If you don't want to have text in the body use this then .TextBody = ""
Note: It is always possible that your firewall block the code (Check your firewall settings)
Can you use CDO on your machine?
Let's try a basic example first.
The code below will send four text lines in the body of the mail to the person in this line
.To = "ron@debruin.nl"
Change ron@debruin.nl to your own mail address before you test the code.
If you read the information above you know that if you have a account in Outlook Express or
Windows Mail you can Run the code below after changing the mail address.
But if you not have a account in Outlook Express or Windows Mail you also need the commented
green lines in the code. Remove every ' before every green line and fill in the name of your SMTP server
where it says "Fill in your SMTP server here"
1) Open a new workbook
2) Alt F11 (to open the VBA editor)
3) Insert>Module
4) Paste the code in this module
5) Make your changes
6) Alt q to go back to Excel
When you use Alt F8 you can select the macro and press Run.
Now wait a moment and see if you receive the mail in your inbox.
Sub CDO_Mail_Small_Text()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
' Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
' iConf.Load -1 ' CDO Source Defaults
' Set Flds = iConf.Fields
' With Flds
' .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
' = "Fill in your SMTP server here"
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
' .Update
' End With
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
With iMsg
Set .Configuration = iConf
.To = "ron@debruin.nl"
.CC = ""
.BCC = ""
.From = """Ron"""
.Subject = "Important message"
.TextBody = strbody
.Send
End With
End Sub
Use the GMail SMTP server from Google.
http://gmail.google.com
You can find the code in the workbook with examples that you can download below.
There is more information about the code in the workbook.
Note: You must have a Gmail account to try this example.
Download workbook with more examples
You can download a example workbook with eighth examples.
Download Example workbook with all the code
Attachment examples:
Module file1 = Workbook
Module file2 = One worksheet or more
Module file3 = Every sheet with a mail address in cell A1
Body examples:
Module body1 = Selection/Range or whole worksheet
Module body2 = Personalized Mail
Module body3 = Every sheet with a mail address in cell A1
Module body4 = Small text and text from a txt file
Note: the body examples in the workbook are using the function RangetoHTML in
the "bodyfunction" module of the workbook.
Gmail example:
Module gmail = Use the smtp.gmail.com server from Gmail to send mail
Tips and links
CDO sheet template
Check out this sheet template if you want to send every sheet to a different person.
Or want to send one or more sheets to one or more recipient.
http://www.rondebruin.nl/mail/templates.htm
Set importance/priority and request read receipt
For importance/priority and read receipt you can add this in the With iMsg part of the macro before .Send
' Set importance or Priority to high
.Fields("urn:schemas:httpmail:importance") = 2
.Fields("urn:schemas:mailheader:X-Priority") = 1
' Request read receipt
.Fields("urn:schemas:mailheader:return-receipt-to") = "ron@debruin.nl"
.Fields("urn:schemas:mailheader:disposition-notification-to") = "ron@debruin.nl"
' Update fields
.Fields.Update
Changing the To line
If you want to mail to all E-mail addresses in a range then use this code
instead of .To = "ron@debruin.nl"
The example below will use the cells from sheets("Sheet1") in ThisWorkbook (workbook with the code)
It is possible that you must use ActiveWorkbook or something else in your code to use it.
Dim cell As Range
Dim strto As String
On Error Resume Next
For Each cell In ThisWorkbook.Sheets("Sheet1") _
.Range("A1:A10").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*@?*.?*" Then
strto = strto & cell.Value & ";"
End If
Next cell
On Error GoTo 0
If Len(strto) > 0 Then strto = Left(strto, Len(strto) - 1)
Change the To line to .To = strto
Or to more people
.To = "Jon@something.com;ron@something.com"
Or you can use a address in a cell like this
.To = Sheets("Sheet1").Range("C1").Value
Change the Body line
Plain text :
Note: see also the example in the workbook to send all text from a txt file (Module body4)
If you want to add more text to the body then you can use the code below.
Instead of .TextBody = "This is the body text" use .TextBody = strbody then.
Dim strbody As String
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
Or use this if you want to use cell values
Dim cell As Range
Dim strbody As String
For Each cell In Sheets("Sheet1").Range("C1:C20")
strbody = strbody & cell.Value & vbNewLine
Next
Or this one
Dim strbody As String
With Sheets("Sheet1")
strbody = "Hi there" & vbNewLine & vbNewLine & _
.Range("A1") & vbNewLine & _
.Range("A2") & vbNewLine & _
.Range("A3") & vbNewLine & _
.Range("A4")
End With
Links
.TextBody = "file://Yourcomputer/YourFolder/Week2.xls"
'If there are spaces use %20
.TextBody = "file://Yourcomputer/YourFolder/Week%202.xls"
'Example for a file on a website
.TextBody = "http://www.rondebruin.nl/files/EasyFilter.zip"
HTML text :
If you want to create emails that are formatted you can use HTMLBody (Office 2000 and up) instead of TextBody. You can find a lot of WebPages on the internet with more HTML tags examples.
.HTMLBody = "
"Please visit this website to download an update.
" & _
"Ron's Excel Page"
Tip: Or send a complete webpage, instead of HTMLBody or TextBody use
.CreateMHTMLBody "http://www.rondebruin.nl/copy1.htm"
Or file on your computer
.CreateMHTMLBody "file://C:/test.htm"
Copy the cells as values
If you want to paste as values the sheet must be unprotected!!!!!
Or Unprotect and Protect the sheet in the Sub also.
See this page for example code that you can use
http://www.rondebruin.nl/values.htm
Test if you are online
You can use code like this in your subroutine to avoid errors if you run the code
when you are not online (example below is for a dial up connection)
For checking other connections check out this great website.
http://vbnet.mvps.org/
Public Declare Function InternetGetConnectedState _
Lib "wininet.dll" (lpdwFlags As Long, _
ByVal dwReserved As Long) As Boolean
Function IsConnected() As Boolean
Dim Stat As Long
IsConnected = (InternetGetConnectedState(Stat, 0&) <> 0)
End Function
Sub Test()
' Randy Birch
If IsConnected = True Then
MsgBox "Copy your mail code here"
Else
MsgBox "You can't use this subroutine because you are not online"
End If
End Sub
Links to more information about CDO for windows 2000
MSDN
Search for "CDO for Windows 2000" on MSDN
Paul R. Sadowski
http://www.paulsadowski.com/WSH/cdo.htm
www.aspfaq.com
http://www.aspfaq.com/show.asp?id=2026
Possível é, mas são tantos os problemas de automação que não vejo o porque de tanta insistência em fazer o código no Excel e/ou outros aplicativos, haja vista que, quem usa o Office, quase sempre está com o Outlook aberto.
É a velha história do InputBox com máscara de senha: basta criar a tela com caixa de texto e alterar a máscara para "*****". Para que inventar códigos mirabolantes para fazer o InputBox receber senha? Ele não foi projetado para isso!
Bem, num dos grupos de Excel que participo recebi esta interessante mensagem sobre como mandar e-mails pelo Excel.
O problema que gerou a discussão, é a mensagem de confirmação que o Outlook exibe quando outro aplicativo tenta enviar e-mails através ele: "confirma (s/n)?".
Não testei o código e nem vou testar, apenas vou deixar registrado aqui para quem quiser se aventurar.
Ah, lembrando também que existe um programa chamado "ClickYes" para quem ainda tem o problema da mensagem de confirmação do Outlook.
abs!
original em: http://www.rondebruin.nl/cdo.htm
Sending mail from Excel with CDO
Ron de Bruin (last update 31-Oct-2007)
Go back to the mail tips page
What is CDO doing
The example code is using CDOSYS (CDO for Windows 2000).
It does not depend on MAPI or CDO and hence is dialog free
and does not use your mail program to send email.
Briefly to explain, this code builds the message and drops it
in the pickup directory, and SMTP service running on the machine
picks it up and send it out to the internet.
Why using CDO code instead of Outlook automation or SendMail in VBA.
1: It doesn't matter what Mail program you are using (It only use the SMTP server).
2: It doesn't matter what Office version you are using (97…2007)
3: You can send a range/sheet in the body of the mail (some mail programs can’t do this)
4: You can send any file you like (Word, PDF, PowerPoint, TXT files,….)
5: No Security warnings anymore, really great if you are sending a lot of mail in a loop.
Read this!!!
This code will not work in Win 98 and ME.
You must be connected to the internet when you run a example.
It is possible that you get a Send error when you use one of the examples.
AFAIK : This will happen if you haven't setup an account in Outlook Express or Windows Mail.
In that case the system doesn't know the name of your SMTP server.
If this happens you can use the commented green lines in each example.
Don't forget to fill in the SMTP server name in each code sample where
it says "Fill in your SMTP server here"
When you also get the Authentication Required Error you can add this three lines.
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "username"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
Don't remove the TextBody line in the code. If you do you can't open the attachment (bug in CDO).
If you don't want to have text in the body use this then .TextBody = ""
Note: It is always possible that your firewall block the code (Check your firewall settings)
Can you use CDO on your machine?
Let's try a basic example first.
The code below will send four text lines in the body of the mail to the person in this line
.To = "ron@debruin.nl"
Change ron@debruin.nl to your own mail address before you test the code.
If you read the information above you know that if you have a account in Outlook Express or
Windows Mail you can Run the code below after changing the mail address.
But if you not have a account in Outlook Express or Windows Mail you also need the commented
green lines in the code. Remove every ' before every green line and fill in the name of your SMTP server
where it says "Fill in your SMTP server here"
1) Open a new workbook
2) Alt F11 (to open the VBA editor)
3) Insert>Module
4) Paste the code in this module
5) Make your changes
6) Alt q to go back to Excel
When you use Alt F8 you can select the macro and press Run.
Now wait a moment and see if you receive the mail in your inbox.
Sub CDO_Mail_Small_Text()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
' Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
' iConf.Load -1 ' CDO Source Defaults
' Set Flds = iConf.Fields
' With Flds
' .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
' = "Fill in your SMTP server here"
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
' .Update
' End With
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
With iMsg
Set .Configuration = iConf
.To = "ron@debruin.nl"
.CC = ""
.BCC = ""
.From = """Ron""
.Subject = "Important message"
.TextBody = strbody
.Send
End With
End Sub
Use the GMail SMTP server from Google.
http://gmail.google.com
You can find the code in the workbook with examples that you can download below.
There is more information about the code in the workbook.
Note: You must have a Gmail account to try this example.
Download workbook with more examples
You can download a example workbook with eighth examples.
Download Example workbook with all the code
Attachment examples:
Module file1 = Workbook
Module file2 = One worksheet or more
Module file3 = Every sheet with a mail address in cell A1
Body examples:
Module body1 = Selection/Range or whole worksheet
Module body2 = Personalized Mail
Module body3 = Every sheet with a mail address in cell A1
Module body4 = Small text and text from a txt file
Note: the body examples in the workbook are using the function RangetoHTML in
the "bodyfunction" module of the workbook.
Gmail example:
Module gmail = Use the smtp.gmail.com server from Gmail to send mail
Tips and links
CDO sheet template
Check out this sheet template if you want to send every sheet to a different person.
Or want to send one or more sheets to one or more recipient.
http://www.rondebruin.nl/mail/templates.htm
Set importance/priority and request read receipt
For importance/priority and read receipt you can add this in the With iMsg part of the macro before .Send
' Set importance or Priority to high
.Fields("urn:schemas:httpmail:importance") = 2
.Fields("urn:schemas:mailheader:X-Priority") = 1
' Request read receipt
.Fields("urn:schemas:mailheader:return-receipt-to") = "ron@debruin.nl"
.Fields("urn:schemas:mailheader:disposition-notification-to") = "ron@debruin.nl"
' Update fields
.Fields.Update
Changing the To line
If you want to mail to all E-mail addresses in a range then use this code
instead of .To = "ron@debruin.nl"
The example below will use the cells from sheets("Sheet1") in ThisWorkbook (workbook with the code)
It is possible that you must use ActiveWorkbook or something else in your code to use it.
Dim cell As Range
Dim strto As String
On Error Resume Next
For Each cell In ThisWorkbook.Sheets("Sheet1") _
.Range("A1:A10").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*@?*.?*" Then
strto = strto & cell.Value & ";"
End If
Next cell
On Error GoTo 0
If Len(strto) > 0 Then strto = Left(strto, Len(strto) - 1)
Change the To line to .To = strto
Or to more people
.To = "Jon@something.com;ron@something.com"
Or you can use a address in a cell like this
.To = Sheets("Sheet1").Range("C1").Value
Change the Body line
Plain text :
Note: see also the example in the workbook to send all text from a txt file (Module body4)
If you want to add more text to the body then you can use the code below.
Instead of .TextBody = "This is the body text" use .TextBody = strbody then.
Dim strbody As String
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
Or use this if you want to use cell values
Dim cell As Range
Dim strbody As String
For Each cell In Sheets("Sheet1").Range("C1:C20")
strbody = strbody & cell.Value & vbNewLine
Next
Or this one
Dim strbody As String
With Sheets("Sheet1")
strbody = "Hi there" & vbNewLine & vbNewLine & _
.Range("A1") & vbNewLine & _
.Range("A2") & vbNewLine & _
.Range("A3") & vbNewLine & _
.Range("A4")
End With
Links
.TextBody = "file://Yourcomputer/YourFolder/Week2.xls"
'If there are spaces use %20
.TextBody = "file://Yourcomputer/YourFolder/Week%202.xls"
'Example for a file on a website
.TextBody = "http://www.rondebruin.nl/files/EasyFilter.zip"
HTML text :
If you want to create emails that are formatted you can use HTMLBody (Office 2000 and up) instead of TextBody. You can find a lot of WebPages on the internet with more HTML tags examples.
.HTMLBody = "
Dear Ron de Bruin
" & _"Please visit this website to download an update.
" & _
"Ron's Excel Page"
Tip: Or send a complete webpage, instead of HTMLBody or TextBody use
.CreateMHTMLBody "http://www.rondebruin.nl/copy1.htm"
Or file on your computer
.CreateMHTMLBody "file://C:/test.htm"
Copy the cells as values
If you want to paste as values the sheet must be unprotected!!!!!
Or Unprotect and Protect the sheet in the Sub also.
See this page for example code that you can use
http://www.rondebruin.nl/values.htm
Test if you are online
You can use code like this in your subroutine to avoid errors if you run the code
when you are not online (example below is for a dial up connection)
For checking other connections check out this great website.
http://vbnet.mvps.org/
Public Declare Function InternetGetConnectedState _
Lib "wininet.dll" (lpdwFlags As Long, _
ByVal dwReserved As Long) As Boolean
Function IsConnected() As Boolean
Dim Stat As Long
IsConnected = (InternetGetConnectedState(Stat, 0&) <> 0)
End Function
Sub Test()
' Randy Birch
If IsConnected = True Then
MsgBox "Copy your mail code here"
Else
MsgBox "You can't use this subroutine because you are not online"
End If
End Sub
Links to more information about CDO for windows 2000
MSDN
Search for "CDO for Windows 2000" on MSDN
Paul R. Sadowski
http://www.paulsadowski.com/WSH/cdo.htm
www.aspfaq.com
http://www.aspfaq.com/show.asp?id=2026
quinta-feira, 16 de abril de 2009
Capturar o nome do usuário via VBA
Muito simples e útil, principalmente quando se precisa de algum tipo diferenciado de acesso conforme o usuário:
Dim usuario As String
usuario = VBA.Environ("username")
MsgBox usuario
;-)
Dim usuario As String
usuario = VBA.Environ("username")
MsgBox usuario
;-)
sexta-feira, 10 de abril de 2009
Minha opinião sobre o Office 2007
Depois de 3 meses trabalhando de segunda a sexta com a dupla "Windows Vista + Office 2007", cheguei as seguintes conclusões:
- É tempo suficiente para formar uma opinião sobre os produtos;
- O Windows Vista é um "comilão" de recursos do hardware sem nada dar em troca do que consome, ou seja, é preciso uma máquina de ponta para ter o Vista e tudo o que você vai ter em troca são apenas alguns recursos visuais "mais bonitinhos". Nada mais;
- O Office 2007 também tem um visual muito mais atraente que a versão anterior, mas para usuários comuns, leia-se "no máximo intermediários", oferece muito pouco pelo que consome;
- A mudança do tradicional menu + barra de ferramentas para a faixa de opções, foi uma mudança infeliz que só dificulta a vida do usuário. E não digam que eu não tentei: personalizei a faixa de opções ao máximo para me adaptar e mesmo assim, depois de 3 meses de uso direto, ainda preciso procurar determinados comandos/recursos;
- Já comentei em algum post no passado que, para a maior parte dos usuários, ainda hoje o Office 97 seria mais que suficiente para o dia a dia e continuo com a mesma opinião. Para que migrar da versão em uso, seja ela 2002 (XP), 2003 ou 2000, para a versão 2007 se você não precisa dos recursos que a nova versão lhe oferece? Por exemplo, é muito bom ter 1 milhão de linhas no Excel, mas quem usa tudo isso?
- Sinceramente, esperava mais do Access 2007 em termos de capacidade e confiabilidade. Meus bancos de dados atuais corrompem com uma frequencia maior do que os criados com o Access 2003 e continuo limitado a 2 Gb;
Resumindo:
A melhor combinação para TRABALHO ainda é o Windows XP + Office 2003.
Palavra de quem usa Vista + Office 2007 todos os dias e não de quem usou algumas vezes para formar a opinião.
Abs!
- É tempo suficiente para formar uma opinião sobre os produtos;
- O Windows Vista é um "comilão" de recursos do hardware sem nada dar em troca do que consome, ou seja, é preciso uma máquina de ponta para ter o Vista e tudo o que você vai ter em troca são apenas alguns recursos visuais "mais bonitinhos". Nada mais;
- O Office 2007 também tem um visual muito mais atraente que a versão anterior, mas para usuários comuns, leia-se "no máximo intermediários", oferece muito pouco pelo que consome;
- A mudança do tradicional menu + barra de ferramentas para a faixa de opções, foi uma mudança infeliz que só dificulta a vida do usuário. E não digam que eu não tentei: personalizei a faixa de opções ao máximo para me adaptar e mesmo assim, depois de 3 meses de uso direto, ainda preciso procurar determinados comandos/recursos;
- Já comentei em algum post no passado que, para a maior parte dos usuários, ainda hoje o Office 97 seria mais que suficiente para o dia a dia e continuo com a mesma opinião. Para que migrar da versão em uso, seja ela 2002 (XP), 2003 ou 2000, para a versão 2007 se você não precisa dos recursos que a nova versão lhe oferece? Por exemplo, é muito bom ter 1 milhão de linhas no Excel, mas quem usa tudo isso?
- Sinceramente, esperava mais do Access 2007 em termos de capacidade e confiabilidade. Meus bancos de dados atuais corrompem com uma frequencia maior do que os criados com o Access 2003 e continuo limitado a 2 Gb;
Resumindo:
A melhor combinação para TRABALHO ainda é o Windows XP + Office 2003.
Palavra de quem usa Vista + Office 2007 todos os dias e não de quem usou algumas vezes para formar a opinião.
Abs!
sábado, 7 de março de 2009
Criando uma pausa na execução do código
Código muito simples, dispensa maiores explicações.
Já vi gente fazendo um "For - Next" sem nada dentro do looping (até funciona...) mas esta é uma solução mais "elegante"!
Já vi gente fazendo um "For - Next" sem nada dentro do looping (até funciona...) mas esta é uma solução mais "elegante"!
Public Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
Public Sub Pausa(ByVal segundos As Single)
Call Sleep(Int(segundos * 1000#))
End Sub
Fechando um processo no TaskManager
A automação no Office nos permite controlar outros aplicativos, mas existe um pequeno "problema" já comentado aqui em um post anterior: mesmo finalizando o aplicativo controlado com "Application.quit" ou limpando a váriavel com "Set var_aplicativo = nothing", o processo continua ativo no gerenciador de tarefas do Windows (TaskManager), o que por vezes pode resultar em erro quando se executa o código duas vezes.
Não sei se isso é um bug ou uma caracterítica do recurso, mas vou deixar aqui um código que elimina o problema.
Obs.: o código não foi escrito por mim, consegui-o nas inúmeras pesquisas pela internet e estou apenas repassando aqui. Já utilizei-o por várias vezes, sempre com sucesso.
Não sei se isso é um bug ou uma caracterítica do recurso, mas vou deixar aqui um código que elimina o problema.
Obs.: o código não foi escrito por mim, consegui-o nas inúmeras pesquisas pela internet e estou apenas repassando aqui. Já utilizei-o por várias vezes, sempre com sucesso.
'Para usar - exemplo:
'Call Closeprocess("Excel.exe")
================================
Option Explicit
Public Const TH32CS_SNAPPROCESS As Long = 2&
Public Const MAX_PATH As Long = 260
Public Type PROCESSENTRY32
dwSize As Long
cntUsage As Long
th32ProcessID As Long
th32DefaultHeapID As Long
th32ModuleID As Long
cntThreads As Long
th32ParentProcessID As Long
pcPriClassBase As Long
dwFlags As Long
szExeFile As String * MAX_PATH
End Type
Public Const PROCESS_ALL_ACCESS As Long = &H1F0FFF
Public Declare Function CreateToolhelp32Snapshot Lib "kernel32" _
(ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Public Declare Function ProcessFirst Lib "kernel32" _
Alias "Process32First" _
(ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Public Declare Function ProcessNext Lib "kernel32" _
Alias "Process32Next" _
(ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Public Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Public Declare Function TerminateProcess Lib "kernel32" _
(ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Public Declare Sub CloseHandle Lib "kernel32" _
(ByVal hPass As Long)
Public Function CloseProcess(EXEName As String) As Boolean
Dim hSnapShot As Long
Dim uProcess As PROCESSENTRY32
Dim hProcess As Long
CloseProcess = False
hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0&)
If hSnapShot = -1 Then Exit Function
uProcess.dwSize = Len(uProcess)
If ProcessFirst(hSnapShot, uProcess) = 1 Then
Do
If LCase$(Left$(uProcess.szExeFile, InStr(1, uProcess.szExeFile, vbNullChar) - 1)) _
= LCase$(EXEName) Then
hProcess = OpenProcess(PROCESS_ALL_ACCESS, False, uProcess.th32ProcessID)
CloseProcess = TerminateProcess(hProcess, ByVal 0&) > 0
Exit Do
End If
Loop While ProcessNext(hSnapShot, uProcess)
End If
Call CloseHandle(hSnapShot)
End Function
A partir de uma planilha, ler dados de outra via ADO
Arquivos XLS não são multiusuários por natureza.
O Excel até permite o compartilhamento, via Ferramentas > Compartilhar Pasta de Trabalho, mas são tantos detalhes que precisam ser observados que o usuário precisa se adaptar ao recurso, sendo que na verdade o recurso deveria facilitar a vida dele.
Recentemente precisei fazer um sistema onde ocorria a leitura de dados de vários XLS's para gravar num outro XLS e este por sua vez, poderia estar aberto no momento da gravação.
Depois de pesquisar, escrever muido código e testar bastante, cheguei a conclusão de que a melhor forma era utilizar o Active Data Objects.
Segue um exemplo de código para leitura de dados de um arquivo XLS a partir de outro.
O melhor de tudo é que podemos utilizar a sintaxe SQL nos comandos, com algumas poucas adaptações é claro, que fará com que os desenvolvedores de banco de dados se sintam bem à vontade.
O Excel até permite o compartilhamento, via Ferramentas > Compartilhar Pasta de Trabalho, mas são tantos detalhes que precisam ser observados que o usuário precisa se adaptar ao recurso, sendo que na verdade o recurso deveria facilitar a vida dele.
Recentemente precisei fazer um sistema onde ocorria a leitura de dados de vários XLS's para gravar num outro XLS e este por sua vez, poderia estar aberto no momento da gravação.
Depois de pesquisar, escrever muido código e testar bastante, cheguei a conclusão de que a melhor forma era utilizar o Active Data Objects.
Segue um exemplo de código para leitura de dados de um arquivo XLS a partir de outro.
O melhor de tudo é que podemos utilizar a sintaxe SQL nos comandos, com algumas poucas adaptações é claro, que fará com que os desenvolvedores de banco de dados se sintam bem à vontade.
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ssql As String
Sub teste()
'cria uma conexão ADO
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
'Na string de conexão, o caracter "aspas duplas" é substituído pelo
'correspondente em ASCII -> Chr(34)
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Planilha.xls" & _
";Extended Properties=" & Chr(34) & "Excel 8.0;HDR=Yes" & Chr(34)
'abre o recordset pelo nome da planilha
'Obs.:
'- No comando SELECT o nome da planilha vai entre chaves e
'com um "$" no final do nome
Set rst = cnn.Execute("Select * from [plan1$]")
MsgBox rst(0)
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End Sub
Importação de arquivos CSV via ADO
Depois que aprendi a trabalhar com o ADO(Active Data Objects), vi que trata-se de um recurso muito flexível e principalmente, fácil de utilizar.
Postarei em breve vários exemplos de utilização do ADO no VBA.
Esta é a dica para importar arquivos texto com os campos separados por vírgula (CSV - Comma Separated Values). Basta copiar o código e ajustar o caminho/nome do arquivo csv:
Postarei em breve vários exemplos de utilização do ADO no VBA.
Esta é a dica para importar arquivos texto com os campos separados por vírgula (CSV - Comma Separated Values). Basta copiar o código e ajustar o caminho/nome do arquivo csv:
Option Explicit
Private Sub importa()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim adcomm As New ADODB.Command
Dim caminho As String
Dim linha As Integer
Dim coluna As Integer
caminho = "D:\paulo\Projetos VB\ADO Arquivo Texto\"
'Conexão para arquivo texto sem cabeçalho:
'connCSV.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
'& caminho & ";Extended Properties='text;HDR=NO;FMT=Delimited'"
'Conexão para arquivo texto com cabeçalho e colunas
cnn.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& caminho & ";Extensions=asc,csv,tab,txt;HDR=NO;Persist Security Info=False"
rst.Open "Select * From TesteDeDados.txt", cnn, adOpenStatic, adLockReadOnly, adCmdText
linha = 1
coluna = 1
Do While Not rst.EOF
Cells(linha, coluna).Value = rst(0)
Cells(linha, coluna + 1).Value = rst(1)
rst.MoveNext
linha = linha + 1
Loop
cnn.Close
Set cnn = Nothing
End Sub
Assinar:
Postagens (Atom)
Pesquisar este blog
Quem sou eu
- Kazu
- Administrador de Empresas/Técnico em Processamento de Dados. Microsoft Office User Specialist - Excel Proficient. Pós-graduado em Business Intelligence.