Jump to content


Photo

Dúvida Vba Excel 2003


  • Faça o login para participar
15 replies to this topic

#1 M3W

M3W

    Novato no fórum

  • Usuários
  • 5 posts
  • Sexo:Masculino
  • Localidade:Sampa

Posted 06/10/2010, 17:23

Boa Tarde
Este é o meu primeiro tópico aqui e espero que algum membro possa me auxiliar


Eu tenho uma macro rodando em uma planilha de excel
e nela tenho 3 sheets (Capa, Dados, Exibição)


Bem na sheet Capa tem um textbox e um botão. O que a pessoa digita no textbox ele faz um filtro em uma coluna da base de dados e filtra o que foi digitado.


Bem o programa roda normalmente no entanto caso a pessoa digite algo que não contenha na coluna onde é realizado o filtro o programa depura.
Eu gostaria de criar um jeito de verificar e ao invés de depurar exiba uma msg de erro para a pessoa para que ela digite novamente.

Meu programa está com o seguinte código
Sub MacroGRUPO()

    Dim varGRUPO As String
    
        varGRUPO = Range("Capa!R1").Value

            Range("PBT!D:D").AutoFilter Field:=1, Criteria1:="=*" & varGRUPO & "*", Operator:=xlAnd
            Range("PBT!A3:BJ40000").Copy
            Range("Dados!A3").PasteSpecial
            Range("PBT!D:D").AutoFilter
            Range("Capa!U2").Select
            ActiveSheet.PivotTables("Tabela Dinâmica Grupo Econômico").PivotCache.Refresh
            Range("A1").Select


Recebi uma dica para adicionar um verificador depois da minha rotina, a principio ele funciona e exibe a msg de erro, mas ele está fazendo isso tanto quando a pessoa digita algo errado qnt quando digita algo correto.

O código fica assim:
Sub MacroGRUPO()
             On Error GoTo TrataErro
    Dim varGRUPO As String
    
        varGRUPO = Range("Capa!R1").Value

            Range("PBT!D:D").AutoFilter Field:=1, Criteria1:="=*" & varGRUPO & "*", Operator:=xlAnd
            Range("PBT!A3:BJ40000").Copy
            Range("Dados!A3").PasteSpecial
            Range("PBT!D:D").AutoFilter
            Range("Capa!U2").Select
            ActiveSheet.PivotTables("Tabela Dinâmica Grupo Econômico").PivotCache.Refresh
            Range("A1").Select
TrataErro:

If Err.Number = X Then
MsgBox "Erro na digitação", vbInformation, "Erro na digitação"
End
Exit Sub
End If
            
End Sub

Espero que alguém possa ajudar.

Obrigado

#2 LeoB

LeoB

    Super Veterano

  • Usuários
  • 1876 posts
  • Sexo:Masculino
  • Interesses:Programação

Posted 06/10/2010, 18:10

Você precisa encerrar a sub antes de começar o tratamento do erro.

Range("A1").Select

Exit Sub

TrataErro:

  • M3W likes this

#3 M3W

M3W

    Novato no fórum

  • Usuários
  • 5 posts
  • Sexo:Masculino
  • Localidade:Sampa

Posted 06/10/2010, 19:09

Boa noite LeoB

Eu fiz isso mas agora está passando direto e depurando quando algo for digitado incorretamente.
O que eu posso fazer ?

Vlw a dica.

#4 LeoB

LeoB

    Super Veterano

  • Usuários
  • 1876 posts
  • Sexo:Masculino
  • Interesses:Programação

Posted 06/10/2010, 19:31

Não pode. Mostre como ficou o código.

#5 M3W

M3W

    Novato no fórum

  • Usuários
  • 5 posts
  • Sexo:Masculino
  • Localidade:Sampa

Posted 07/10/2010, 14:18

Boa tarde LeoB

O código ficou assim:

Sub MacroGRUPO()
On Error GoTo TrataErro
    Dim varGRUPO As String
    
        varGRUPO = Range("Capa!R1").Value
            Range("PBT!D:D").AutoFilter Field:=1, Criteria1:="=*" & varGRUPO & "*", Operator:=xlAnd
            Range("PBT!A3:BJ40000").Copy
            Range("Dados!A3").PasteSpecial
            Range("PBT!D:D").AutoFilter
            Range("Capa!U2").Select
            ActiveSheet.PivotTables("Tabela Dinâmica Grupo Econômico").PivotCache.Refresh
            Range("A1").Select
                Exit Sub
TrataErro:
            If Err.Number = X Then
                MsgBox "Erro na digitação Y", vbInformation, "Erro na digitação"
                End
                Exit Sub
            End If


End Sub

Bem com o código assim quando a pessoa digita algo que contém na coluna tudo funciona normalmente.
Mas quando digitado algo que não contém ele ta passando direto p/ parte seguinte e depurando mais a frente do programa onde deveriam ter os dados que foram filtrados.


Obrigado

#6 LeoB

LeoB

    Super Veterano

  • Usuários
  • 1876 posts
  • Sexo:Masculino
  • Interesses:Programação

Posted 07/10/2010, 19:09

Está depurando dentro dessa sub mesmo? Pra que linha o cursor vai? E tira esse End e o Exit Sub de dentro do If. Não são necessários.

#7 M3W

M3W

    Novato no fórum

  • Usuários
  • 5 posts
  • Sexo:Masculino
  • Localidade:Sampa

Posted 08/10/2010, 15:19

Bem sem esse código para identifiar o erro o que acontece é que quando eu clico no botão de busca a macro faz um filtro em uma coluna e com o que estiver numa celula ele ele faz o filtro.

O programa roda normalmente sem problemas, mas se a célula tiver uma palavra que não tem na coluna a macro depura
Erro em tempo de execução '308':
Não foi possível definir a propriedade ListIndex. Valor de propriedade inválido


Quando termina o macro da sequência a minha programação que é a seguinte

Private Sub cmdGRUPO_Click()

	cbxGRUPO.Enabled = True
	cmdCONFIRMAR.Enabled = True
	Geconomico = txtGRUPO.Text
	cmdPesquisar.Enabled = True

		Range("Capa!S5").Value = "Desativado"
	
			If Geconomico = "" Then
				MsgBox " Digite o Grupo Econômico "
	
			Else
				UCase (Geconomico)
				Range("Capa!R1") = Geconomico
					Call Módulo1.MacroGRUPO
										
					
						cbxGRUPO.Clear
						Range("Capa!AB1").Select
						Preencher = True
							Do While Preencher = True
								ActiveCell.Offset(1, 0).Select
								If ActiveCell.Value = vbNullString Then
									Preencher = False
								Else
									cbxGRUPO.AddItem ActiveCell.Value
								End If
							Loop
								(cbxGRUPO.ListIndex = 0)
									Range("Capa!A1").Select
		
			End If
			
End Sub
A linha entre parenteses é onde a macro depura sem o código de verificação
Sub MacroGRUPO()
'On Error GoTo TrataErro
	Dim varGRUPO As String
	
		varGRUPO = Range("Capa!R1").Value
			Range("PBT!D:D").AutoFilter Field:=1, Criteria1:="=*" & varGRUPO & "*", Operator:=xlAnd
			Range("PBT!A3:BJ40000").Copy
			Range("Dados!A3").PasteSpecial
			Range("PBT!D:D").AutoFilter
			Range("Capa!U2").Select
			ActiveSheet.PivotTables("Tabela Dinâmica Grupo Econômico").PivotCache.Refresh
			Range("A1").Select

'TrataErro:
'			If Err.Number = X Then
'				MsgBox "Erro na digitação", vbInformation, "Erro na digitação"
'				End
'				Exit Sub
'			End If


End Sub

Quando eu ativo o tratamento do erro, ele manda a msg caso o que tenha na célula não contenha na coluna e exibe a msg Erro na digitação, mas ele também exibe a msg se a célular tiver um conteúdo que contenha na coluna.

Ou seja ele ta parando o programa mesmo se a célula estiver com um valor válido ou não.



Espero ter sido o mais detalhado possível.


Obrigado

#8 LeoB

LeoB

    Super Veterano

  • Usuários
  • 1876 posts
  • Sexo:Masculino
  • Interesses:Programação

Posted 08/10/2010, 19:08

Primeiro ponto: você está fazendo o tratamento do erro dentro de Modulo1.MacroGRUPO sendo que o erro é fora dela. Portanto, você precisa fazer aquele tratamento com o On Error e tudo mais no cmdGRUPO_Click().

Segundo ponto: o problema acontece porque cbxGRUPO fica vazio, concorda? Sendo assim, você pode evitar o erro simplesmente verificando se cbxGRUPO.Count > 0 antes de prosseguir depois do loop. Se não for, mostra a msgbox ou o que você quiser. Esta opção deve ter preferência em relação à anterior.
  • M3W likes this

#9 M3W

M3W

    Novato no fórum

  • Usuários
  • 5 posts
  • Sexo:Masculino
  • Localidade:Sampa

Posted 11/10/2010, 13:54

Consegui resolver LeoB

Fiz o código de verificação onde ocorre o erro cmdGRUPO
e no x coloquei o número do erro '380'


Agora está funcionando perfeitamente.


Muito obrigado pela ajuda.

Vlw

#10 RonsisM

RonsisM

    Super Veterano

  • Usuários
  • 15724 posts
  • Sexo:Masculino
  • Localidade:Plovdiv

Posted 18/09/2017, 18:44

Acheter Tadalafil online pharmacy Purchase Discount Doxycycline Viagra Su?Igkeiten Domperidone Illegal Lasix Without Prescriptions viagra cialis Donde Comprar Levitra Generico En Espana
Cheap Brand Viagra Online cialis Nolvadex En Pharmacie
Cialis Farmacie Online Pak Zithromax
Progesterone Store <a href=http://cialtobuy.com>cialis</a> Propecia Hsa Cialis

#11 RonsisM

RonsisM

    Super Veterano

  • Usuários
  • 15724 posts
  • Sexo:Masculino
  • Localidade:Plovdiv

Posted 04/10/2017, 15:14

Good Online Place To Buy Viagra viagra online Discount Clobetasol Amex Worldwide Buy Kamagra Pills
Ajanta Pharma Kamagra Oral Jelly Accutane Online India viagra Levitra Ohne Kreditkarte
Lean Tea levitra without prescription Biomox Amoxicillin
Sildenafil 50mg Tablets To Buy cialis La Viagra Se Puede Comprar Sin Receta

#12 RonsisM

RonsisM

    Super Veterano

  • Usuários
  • 15724 posts
  • Sexo:Masculino
  • Localidade:Plovdiv

Posted 13/10/2017, 15:52

Levitra Non Funziona Triamterene Hctz 375 25 Mg online pharmacy Dosage Of Amoxicillin For Lyme Viagra Generica En Espana
Buy Propecia Online Uk No Prescription Viagra Prostatite Amoxicillin Low Cost viagra Amoxicillin Trihydrate Clavulanate Potassium Le Cialis En Tunisie
Rxpillshop Cytotec En Gynecologie viagra Propecia Results How Long Before
Real Viagra 150mg Blue viagra Levitra Comentarios Cialis Interazioni Farmaci Priligy Blood Pressure

#13 hapedlok

hapedlok

    24 Horas

  • Usuários
  • 499 posts
  • Sexo:Feminino
  • Localidade:Brisbane

Posted 18/10/2017, 22:26

Discounts! best summer beauty products 2017 progect11.jpg Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked! If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included). buy.png READ MORE New 2016 women handbags leather handbag women messenger bags ladies brand designs bag bags handbag+messenger bag+purse 3 sets ( 45.88 $)Black mask face mask blackhead remover deep cleansing purifying the black head acne treatments face mask ( 2.78 $)Rc icon gold tone metal earrings wcrystals ( 507.13 $) Roberto Cavalli2016 festival Memorial Day gift Enmex women creative slim strap wristwatch brief design elegance fashion quartz lady watches ( 12.40 $)CUBOT Cheetahphone Android 6.0 5.5 inch 4G Phablet 2.5D Arc Screen MTK6753 64bit Octa Core 1.5GHz 3GB RAM 32GB ROM Fingerprint Sensor 13MP Main Camera 5G WiFi Bluetooth 4.0 202.59$7A Brazilian Virgin Hair With Closure 3 Bundles With Closure Brazilian Body Wave With Closure Human Hair Bundles With Closure ( 67.00 $)7a brazilian virgin hair straight human hair weave 4 bundles brazilian straight hair extension mink brazilian hair weave bundles ( 50.00 $)Acevog brand s - 4xl women dress retro vintage 1950s 60s rockabilly floral swing summer dresses elegant bow-knot tunic vestidos ( 30.42 $)TenFifteen Q7SE Smartwatch Phone-35.53 $Discovery V8 3G Smartphone-71.39 $Purple wedding dress shoes high heel rhinestone bridal shoes 4 inch banquet party prom pumps elegant shoes for wedding ceremony ( 100.79 $)Phase precious fan sterling silver ring ( 262.12 $) Vojd StudiosPeruvian Virgin Hair Straight 4 Bundles Deals 7A Human Hair Weave Peruvian Straight Virgin Hair Bundles Rosa Hair Products ( 51.10 $)Pozner i Litvinova izvinilis pered uchastnikom «Minuti slavi» (Video)Klarus Mi02 UV Mini LED Flashlight ( $6.18 ) 8bb.jpg
Discounts! the product review

progect11.jpg
Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked!
If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included).

buy.png

READ MORE
Elephone Elecam 360 WiFi Action Camera Dual Lens-200.15 $
Brazilian virgin hair straight 7a virgin brazilian straight hair 4 bundles mink brazilian straight virgin human hair bundle deal ( 76.80 $)
8A Italian Yaki Full Lace Human Hair Wigs For Black Women Brazilian Full Lace Hair Wig 8-24"" Yaki Lace Front Human Hair Wigs ( 87.00 $)
2016 new the joker 3d t shirt funny comics character joker with poker 3d t-shirt summer style outfit tees top full printing ( 12.70 $)
2015 new design h4 led headlight cars high low beam 40w fog light kit led lamp xenon car-styling h4 led bulbs for cars ( 39.99 $)
Smart Tiger Intelligent Dimmable LED Lamp-22.18 $
MIPOW Power Tube 10000 8000mAh Mobile Power Bank-26.48 $
Men's casual solid color cargo shorts ( 15.74 $)
Malikah gold leather flat sandal ( 347.71 $) Oscar Tiye
Animal Print Haircalf Leather Belt ( 144.00 $)
Poisk kartinok po izobrazheniyu Nedavno…
Mens Tan Perforated Leather Belt ( 135.00 $)
«I ne lyubov uzhe nichkom»
XINDA XD - A9501 Harness Bust Seat Belt Outdoor Rock Climbing Harness Rappelling Equipment Harness Seat Belt with Carrying Bag ( 37.07 $)
2016white peel off liquid nail art tape latex tape finger skin protected liquid palisade easy clean ( 1.75 $)


36.jpg

#14 RonsisM

RonsisM

    Super Veterano

  • Usuários
  • 15724 posts
  • Sexo:Masculino
  • Localidade:Plovdiv

Posted 30/10/2017, 21:42

Amoxicillin Resistant Dental Cialis Active Over The Counter Online Free Shipping Dutasteride Find Secure Ordering Free Consultation Carlisle buy cialis Cialis Differenza Viagra Best Buy Isotretinoin Skin Health No Doctor London
Caphalexin Sandoz Vs Cephalexin Ialex viagra Viagra Medicitalia
Cephalexin Trigger Imha Buy Kamagra In Bali Propecia Decadencia De Pelo cialis Priligy Erfaringer Il Cialis Si Trova In Farmacia

#15 RonsisM

RonsisM

    Super Veterano

  • Usuários
  • 15724 posts
  • Sexo:Masculino
  • Localidade:Plovdiv

Posted 17/11/2017, 21:16

Propecia Pas Cher 2011 Amoxicillin And Sandoz viagra Amoxicillin Chlamydia Single Dose Vente Viagra Ligne France En Lille Buy Colchicine Tablets
Levitra Farmaco cialis Cephalexin 500 Mgs Twice A Day Viagra Para La Eyaculacion Precoz Cephalexin Mod
Viagra Wirkung Mann Cheap Viagra Pills For Sale viagra Acheter Levitra Pas Cher Rezeptfreie Levitra
Buy 5mg Cialis Online Viagra Wurzel Cheapest Kamagra Uk viagra Kamagra Bestellen Wo 20 Mg Lisinopril Sale No Perscription




1 user(s) are reading this topic

0 membro(s), 1 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq