I a newbie to MS Access and VBA Code, but I have been handling well my needs. The code posted bellow is the only way I got my Click Event working. In order to printout current record from multiple tables (mail merge) it's required that some fields are filled. So before the actual printout code I inserted the following code. Is there a better way to do it? It just doesn't feel right the way I did it.
If IsNull(Screen.ActiveForm![Nome]) Then
MsgBox "Preencher o Nome do Cliente."
Screen.ActiveForm![Nome].SetFocus
Else
If IsNull(Screen.ActiveForm![Gênero]) Then
MsgBox "Preencher o Gênero do Cliente."
Screen.ActiveForm![Gênero].SetFocus
Else
If IsNull(Screen.ActiveForm![Estado Civíl]) Then
MsgBox "Preencher o Estado Civíl do Cliente."
Screen.ActiveForm![cboecivil].SetFocus
Else
If IsNull(Screen.ActiveForm![Profissão]) Then
MsgBox "Preencher a Profissão do Cliente."
Screen.ActiveForm![Profissão].SetFocus
Else
If IsNull(Screen.ActiveForm![CEP]) Then
MsgBox "Preencher o CEP do Cliente."
Screen.ActiveForm![CEP].SetFocus
Else
If IsNull(Screen.ActiveForm![Endereço]) Then
MsgBox "Preencher o nome da Rua do Cliente."
Screen.ActiveForm![Endereço].SetFocus
Else
If IsNull(Screen.ActiveForm![Número]) Then
MsgBox "Preencher o Número da Rua do Cliente."
Screen.ActiveForm![Número].SetFocus
Else
If IsNull(Screen.ActiveForm![Cidade]) Then
MsgBox "Preencher a Cidade do Cliente."
Screen.ActiveForm![Cidade].SetFocus
Else
If IsNull(Screen.ActiveForm![UF]) Then
MsgBox "Preencher o Estado do Cliente."
Screen.ActiveForm![UF].SetFocus
Else
If IsNull(Screen.ActiveForm![Bairro]) Then
MsgBox "Preencher o Bairro do Cliente."
Screen.ActiveForm![Bairro].SetFocus
Else
If IsNull(Screen.ActiveForm![Complemento]) Then
MsgBox "Preencher o Complemento do Endereço do Cliente."
Screen.ActiveForm![Complemento].SetFocus
Else
If IsNull(Forms("Painel de Controle").sftblCPF.Form.CPF) Then
MsgBox "Preencher o CPF do Cliente."
Forms("Painel de Controle").sftblCPF.Form.CPF.SetFocus
Else
If IsNull(Forms("Painel de Controle").sftblRG.Form.Número) Then
MsgBox "Preencher o Número do RG do Cliente."
Forms("Painel de Controle").sftblRG.Form.Número.SetFocus
Else
If IsNull(Forms("Painel de Controle").sftblRG.Form.Série) Then
MsgBox "Preencher a Série do RG do Cliente."
Forms("Painel de Controle").sftblRG.Form.Série.SetFocus
Else
If IsNull(Forms("Painel de Controle").sftblRG.Form.[Orgão Emissor]) Then
MsgBox "Preencher o Orgão Emissor do RG do Cliente."
Forms("Painel de Controle").sftblRG.Form.[Orgão Emissor].SetFocus
Else
If Forms("Painel de Controle").sftblCPF.Form.[Principal?] = False Then
MsgBox "Marcar o CPF Principal do Cliente."
Forms("Painel de Controle").sftblCPF.Form.[Principal?].SetFocus
Else
If Forms("Painel de Controle").sftblRG.Form.[Principal?] = False Then
MsgBox "Marcar o RG Principal do Cliente."
Forms("Painel de Controle").sftblRG.Form.[Principal?].SetFocus
Else
'MailMerge code inserted Here.
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Put all the field names into an array
Dim fieldNames As Variant
Private Sub Form_Load()
fieldNames = Array("Nome", "Gênero", "Estado Civíl", "Profissão", ...)
End Sub
then use a loop to do the checks
Dim fieldName As String
Dim i As Long
For i = LBound(fieldNames) To UBound(fieldNames)
fieldName = fieldNames(i)
If IsNull(Screen.ActiveForm(fieldName).Value) Then
MsgBox "Preencher o " & fieldName & " do Cliente."
Screen.ActiveForm(fieldName).SetFocus
Exit Sub
End If
Next i
If you need individually composed messages, you can use a second array with messages:
Dim fieldNames As Variant
Dim messages As Variant
Private Sub Form_Load()
fieldNames = Array("Nome", "Gênero", "Estado Civíl", "Profissão", ...)
messages = Array("Preencher o Nome do Cliente.", "Preencher o Gênero ...", ...)
End Sub
then use a loop again to do the checks
Dim fieldName As String
Dim i As Long
For i = LBound(fieldNames) To UBound(fieldNames)
fieldName = fieldNames(i)
If IsNull(Screen.ActiveForm(fieldName).Value) Then
MsgBox messages(i)
Screen.ActiveForm(fieldName).SetFocus
Exit Sub
End If
Next i
Btw., you can use an ElseIf instead of an Else followed by an If. This will chain the conditions instead of nesting them
If IsNull(Screen.ActiveForm![Nome]) Then
MsgBox "Preencher o Nome do Cliente."
Screen.ActiveForm![Nome].SetFocus
ElseIf IsNull(Screen.ActiveForm![Gênero]) Then
MsgBox "Preencher o Gênero do Cliente."
Screen.ActiveForm![Gênero].SetFocus
ElseIf IsNull(Screen.ActiveForm![Estado Civíl]) Then
MsgBox "Preencher o Estado Civíl do Cliente."
Screen.ActiveForm![cboecivil].SetFocus
ElseIf IsNull(Screen.ActiveForm![Profissão]) Then
MsgBox "Preencher a Profissão do Cliente."
Screen.ActiveForm![Profissão].SetFocus
...
End If
See: If...Then...Else Statement (Visual Basic)
If you make the fields themselves required on the table then the record can't be saved until it is completed. If there are fields that are required at different steps, make sure the tables are normalized in a way that each step doesn't have required fields that are required on different steps.
When it comes time to make the form with all the required fields in one place, make a query that pulls all the fields from all the tables needed in one query. Base the form on that query. You can edit fields in a properly formed query so this will just work when you get it right.
Once you have your backend defined properly this way the front end interface has built in warnings that won't allow the form to save if required fields are missing. There is a total of zero VBA code required to get this to work.
In the end you will have a more normalized database with better safety controls to avoid invalid states. You will also find performance improvements that come with properly indexing, relating, and constraining the tables.
First of all, I would like to thank you all for the explanations. You have no idea how helpful it was. I ended up using the second example Olivier advised. Due to the need of prompt text variety, I could not use the first option.
The fields are not essentially necessary for the DataBase, but they are mandatory for some buttons events I built to export data to MailMerge Document. Which, by the way, it was really hard to do, since I have data from multiple tables (as subforms) in this form and I needed only the current record to be merged. To make it work I created a parameter query indexed to the form's current ClientID, than VBA code to insert that data into to a pre-created single record table where my MailMerged Documents pulls the information from. I also used a code to create a ClientFolder's Name if not created already. I don't know if this procedure is safe for the DataBase, but I really could not find any other way to do it. I will post the full code bellow, so other people can check and use it.
HackSlash, I struggled a lot with this Form because every time I tried to use a query as source, I wasn't able to edit it. With that, I used the table that had most needed information and a lot of subforms (for two reasons). First, some fields that I need on the Form has one-to-many relationship (like ClientComments, ClientePhoneNumbers, ...), second, since I didn't know I was able to edit a query source, I had to use subforms as a Text Field to place the related information on the form. I will definitely check the article you posted and try out sourcing this form with a query. One more time, Thank you very much!
Private Sub cmdProcuração_Click()
If IsNull(Screen.ActiveForm![Nome]) Then
MsgBox "Preencher o Nome do Cliente."
Screen.ActiveForm![Nome].SetFocus
ElseIf IsNull(Screen.ActiveForm![Gênero]) Then
MsgBox "Preencher o Gênero do Cliente."
Screen.ActiveForm![Gênero].SetFocus
ElseIf IsNull(Screen.ActiveForm![Estado Civíl]) Then
MsgBox "Preencher o Estado Civíl do Cliente."
Screen.ActiveForm![cboecivil].SetFocus
ElseIf IsNull(Screen.ActiveForm![Profissão]) Then
MsgBox "Preencher a Profissão do Cliente."
Screen.ActiveForm![Profissão].SetFocus
ElseIf IsNull(Screen.ActiveForm![CEP]) Then
MsgBox "Preencher o CEP do Cliente."
Screen.ActiveForm![CEP].SetFocus
ElseIf IsNull(Screen.ActiveForm![Endereço]) Then
MsgBox "Preencher o nome da Rua do Cliente."
Screen.ActiveForm![Endereço].SetFocus
ElseIf IsNull(Screen.ActiveForm![Número]) Then
MsgBox "Preencher o Número da Rua do Cliente."
Screen.ActiveForm![Número].SetFocus
ElseIf IsNull(Screen.ActiveForm![Cidade]) Then
MsgBox "Preencher a Cidade do Cliente."
Screen.ActiveForm![Cidade].SetFocus
ElseIf IsNull(Screen.ActiveForm![UF]) Then
MsgBox "Preencher o Estado do Cliente."
Screen.ActiveForm![UF].SetFocus
ElseIf IsNull(Screen.ActiveForm![Bairro]) Then
MsgBox "Preencher o Bairro do Cliente."
Screen.ActiveForm![Bairro].SetFocus
ElseIf IsNull(Screen.ActiveForm![Complemento]) Then
MsgBox "Preencher o Complemento do Endereço do Cliente."
Screen.ActiveForm![Complemento].SetFocus
ElseIf IsNull(Forms("Painel de Controle").sftblCPF.Form.CPF) Then
MsgBox "Preencher o CPF do Cliente."
Forms("Painel de Controle").sftblCPF.Form.CPF.SetFocus
ElseIf IsNull(Forms("Painel de Controle").sftblRG.Form.Número) Then
MsgBox "Preencher o Número do RG do Cliente."
Forms("Painel de Controle").sftblRG.Form.Número.SetFocus
ElseIf IsNull(Forms("Painel de Controle").sftblRG.Form.Série) Then
MsgBox "Preencher a Série do RG do Cliente."
Forms("Painel de Controle").sftblRG.Form.Série.SetFocus
ElseIf IsNull(Forms("Painel de Controle").sftblRG.Form.[Orgão Emissor]) Then
MsgBox "Preencher o Orgão Emissor do RG do Cliente."
Forms("Painel de Controle").sftblRG.Form.[Orgão Emissor].SetFocus
ElseIf Forms("Painel de Controle").sftblCPF.Form.[Principal?] = False Then
MsgBox "Marcar o CPF Principal do Cliente."
Forms("Painel de Controle").sftblCPF.Form.[Principal?].SetFocus
ElseIf Forms("Painel de Controle").sftblRG.Form.[Principal?] = False Then
MsgBox "Marcar o RG Principal do Cliente."
Forms("Painel de Controle").sftblRG.Form.[Principal?].SetFocus
Else
On Error GoTo ErrorHandler
'A seguir comandos para modificar a tabela existente com os dados atuais do formulário (Organizados em uma Consulta)
DoCmd.SetWarnings False
DoCmd.RunSQL "SELECT * INTO [tblExportarDocumentos] FROM [Exportar Contatos]" '(FROM QUERY)
DoCmd.SetWarnings True
Dim strSql As String
'Instrução SQL direto da tabela criada
strSql = "SELECT * FROM [tblExportarDocumentos]"
Dim strDocumentName As String 'Nome do Documento Template com a subpasta
strDocumentName = "\Documentos\Procuração RCT.docx"
Dim strNewName As String 'Nome usado para Salvar o Documento
strNewName = "Procuração - " & Nome.Value
Call OpenMergedDoc(strDocumentName, strSql, strNewName)
Exit Sub
ErrorHandler:
MsgBox "Error #" & Err.Number & " occurred. " & Err.Description,
vbOKOnly, "Error"
Exit Sub
End If
End Sub
Private Sub OpenMergedDoc(strDocName As String, strSql As String, s
trMergedDocName As String)
On Error GoTo WordError
Const strDir As String = "C:\Users\Jcnra\Documents\Banco de Dados RCT"
'Localização da pasta com o Banco de Dados
Dim objWord As New Word.Application
Dim objDoc As Word.Document
objWord.Application.Visible = True
Set objDoc = objWord.Documents.Open(strDir & strDocName)
objWord.Application.Visible = True
'A seguir, a função do Mail Merge. Em Name: Colocar o endereço exato do arquivo do Banco de Dados
'Em SQLStatement: Colocar a mesma função sql acima
objDoc.MailMerge.OpenDataSource _
Name:="C:\Users\Jcnra\Documents\Banco de Dados RCT\Backup Banco de
Dados RCT.accdb", _
LinkToSource:=True, AddToRecentFiles:=False, _
Connection:="", _
SQLStatement:="SELECT * FROM [tblExportarDocumentos]"
'A seguir, condição para criar pastas no diretório, caso já não existam
If Dir(strDir & "\Clientes\" & Nome.Value, vbDirectory) = "" Then
MkDir (strDir & "\Clientes\" & Nome.Value)
Else
End If
objDoc.MailMerge.Destination = wdSendToNewDocument
objDoc.MailMerge.Execute
'Comando para salvar o Documento criado
objWord.Application.Documents(1).SaveAs (strDir & "\Clientes\" &
Nome.Value & "\" & strMergedDocName & ".docx")
objWord.Application.Documents(2).Close wdDoNotSaveChanges
objWord.Visible = True
objWord.Activate
objWord.WindowState = wdWindowStateMaximize
'Liberar as variáveis
Set objWord = Nothing
Set objDoc = Nothing
Exit Sub
WordError:
MsgBox "Err #" & Err.Number & " occurred." & Err.Description,
vbOKOnly, "Word Error"
objWord.Quit
End Sub
Related
I'm writing a script to help myself with my work and I've never coded with VBA before this. Actually, i wrote this (partially, got a couple functions from other macros) but i don't understand it perfectly.
So the script is supposed to get some values from the equation manager table, display them in a textbox and when the user presses Go the values are updated with the new input values. The values are being transformed from "4.5" to "45" in one of the input boxes
the code is
Attribute VB_Name = "Modulo"
Option Explicit
Dim swApp As SldWorks.SldWorks 'Declara Variavel da Aplicação
Dim swModel As SldWorks.ModelDoc2 'Declara Variavel do Modelo
Public Larg, Comp, Alt As Double 'Declara Variavel Publica para os valores atuais do Modelo
Public AltT, RaioT, QntdPrat As Double 'Declara variaveis para testeira e pirulito
Public EspessuraEstrutural As Double 'Declara Variaveis para Espessura
Public NLarg, NComp, NAlt As Double 'Declara Variavel Publica para os Novos Valores
Public NAltT, NRaioT, NQntdPrat As Double 'Declara Variaveis para Novos valores
Public NEspessuraEstrutural As Double 'Declara Variaveis para Novos valores
Public contadorDeParametros 'numero de parametros
Sub main()
Set swApp = Application.SldWorks 'Atribui A aplicação atual à variavel
Set swModel = swApp.ActiveDoc 'Atribui A Modelo atual à variavel
If Not swModel Is Nothing Then 'Checa se o modelo não está vazio
Dim swEqMgr As SldWorks.EquationMgr 'Declara Variavel para a tabela de equações
Set swEqMgr = swModel.GetEquationMgr 'Atribui a tabela de equações Para a Variavel
Comp = swEqMgr.value(1) 'Atribui o valor atual para a variavel
Larg = swEqMgr.value(0) 'Atribui o valor atual para a variavel
Alt = swEqMgr.value(2) 'Atribui o valor atual para a variavel
AltT = swEqMgr.value(10) 'Atribui o valor atual para a variavel
RaioT = swEqMgr.value(15) 'Atribui o valor atual para a variavel
EspessuraEstrutural = swEqMgr.value(3) 'Atribui o valor atual para a variavel
QntdPrat = swEqMgr.value(11)
UserForm1.TextComp.Text = Comp 'Exibe o valor atual na interface
UserForm1.TextLarg.Text = Larg 'Exibe o valor atual na interface
UserForm1.TextAlt.Text = Alt 'Exibe o valor atual na interface
UserForm1.TextAltT.Text = AltT 'Exibe o valor atual na interface
UserForm1.TextRaioT.Text = RaioT 'Exibe o valor atual na interface
UserForm1.TextEspessuraEstrutural.Text = EspessuraEstrutural 'Exibe o valor atual na interface
UserForm1.TextQntdPrat.Text = QntdPrat 'Exibe o valor atual na interface
End If
UserForm1.Show vbModeless 'Exibe a inteface com a opção de não travar o foco
End Sub
Public Sub AlteraEq() 'Função publica para alterar as dimensões se elas forem diferentes da dimensão original
Dim modelo As SldWorks.ModelDoc2 'Declara Variavel da Aplicação da funcao
Dim aplicacao As SldWorks.SldWorks 'Declara Variavel da Aplicação da funcao
Dim tabelaEQ As SldWorks.EquationMgr 'Declara Variavel da Aplicação da funcao
Set aplicacao = Application.SldWorks 'Atribui A aplicação atual à variavel da funcao
Set modelo = aplicacao.ActiveDoc 'Atribui o Modelo atual à variavel da funcao
Set tabelaEQ = modelo.GetEquationMgr 'Atribui A tabela de equações atual à variavel da funcao
NullCatch Comp, NComp, "Comprimento", tabelaEQ
NullCatch Larg, NLarg, "Largura", tabelaEQ
NullCatch Alt, NAlt, "Altura", tabelaEQ
NullCatch AltT, NAltT, "AlturaTesteira", tabelaEQ
NullCatch RaioT, NRaioT, "FilletTesteira", tabelaEQ
NullCatch EspessuraEstrutural, CStr(NEspessuraEstrutural), "EspessuraChapa", tabelaEQ
NullCatch QntdPrat, NQntdPrat, "QuantidadePrateleiras", tabelaEQ
End Sub
Sub NullCatch(valor, novoValor, Parametro As String, Tabela As SldWorks.EquationMgr)
If Not novoValor = valor Then 'Checa se O novo valor e o valor anterior são iguais
If SetEquationValue(Tabela, Parametro, CDbl(novoValor)) Then 'executa a função que altera a Tabela com os novos parametros
swModel.ForceRebuild3 True 'Força o modelo a ser reconstruido com os novos parametros
Else 'Senao
MsgBox "Failed to find the equation " & Parametro 'Exibe mensagem de erro
End If
End If
End Sub
Function SetEquationValue(eqMgr As SldWorks.EquationMgr, name As String, value As Double) As Boolean 'Funcao para alterar valor de uma equacao
Dim index As Integer 'Declara Variavel para index como integer
index = GetEquationIndexByName(eqMgr, name) 'Atribui o index da equacao usando o nome atraves de outra funcao
If index <> -1 Then 'Checa se o index é valido
eqMgr.Equation(index) = """" & name & """=" & value 'Altera o valor da equação
SetEquationValue = True 'Retorna Verdadeiro para a função
Else 'Senao
SetEquationValue = False 'Retorna falso para a função
End If
End Function
Function GetEquationIndexByName(eqMgr As SldWorks.EquationMgr, name As String) As Integer 'Funcao para obter index por nome
Dim i As Integer 'Declara uma variavel para usar no loop
GetEquationIndexByName = -1 'define o retorno da funcao para -1(valor invalido usado para sinalizar o fim da lista)
For i = 0 To eqMgr.GetCount - 1 'Loop que vai de 0 ao fim da lista de equações
Dim eqName As String 'Declara Variavel para o nome da equação atual do loop
eqName = Trim(Split(eqMgr.Equation(i), "=")(0)) 'remove tudo após o = na função
eqName = Mid(eqName, 2, Len(eqName) - 2) 'Remove os paranteses do nome
If UCase(eqName) = UCase(name) Then 'Compara o nome dado como parametro da função com o nome da equacao atual do loop
GetEquationIndexByName = i 'Se é igual retorna o valor do index para a função
Exit Function
End If
Next
End Function
And the code for the userform is
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} UserForm1
Caption = "UserForm1"
ClientHeight = 4815
ClientLeft = 120
ClientTop = 465
ClientWidth = 4230
OleObjectBlob = "UserForm1.frx":0000
StartUpPosition = 1 'CenterOwner
End
Attribute VB_Name = "UserForm1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim swApp As SldWorks.SldWorks
Dim swModel As ModelDoc2
Private Sub UserForm_Activate()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
Public Sub Butao_Click()
Modulo.NComp = UserForm1.TextComp.Text
Modulo.NLarg = UserForm1.TextLarg.Text
Modulo.NAlt = UserForm1.TextAlt.Text
Modulo.NRaioT = UserForm1.TextRaioT.Text
Modulo.NAltT = UserForm1.TextAltT.Text
Modulo.NEspessuraEstrutural = UserForm1.TextEspessuraEstrutural.value
Modulo.NQntdPrat = UserForm1.TextQntdPrat.Text
Call Modulo.AlteraEq
UserForm1.Hide
End Sub
The var that is giving me trouble is the "EspessuraEstrutural" but all variables are set up the same so i don't know if this info is useful
I have a function that receives a PDF file from the desktop. What I want is that, before saving the PDF, deactivate the clipboard so that they cannot copy the text or images of the document.
My code:
Dim NombreArchivo As String = System.IO.Path.GetFileName(File1.PostedFile.FileName) ' obtiene nombre archivo
Dim docsubido As New Document()
Dim SaveLocation As String = Server.MapPath("Pdf") & "\" & NombreArchivo ' obtiene ruta donde se guardara
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
File1.PostedFile.SaveAs(SaveLocation)
Response.Write("El archivo ha sido cargado.")
Catch Exc As Exception
Response.Write("Error: " & Exc.Message)
End Try
Else
Response.Write("Seleccione un archivo para cargar.")
End If
End Sub
Finally this was the solution to be able to disable the property of copying and pasting of a PDF only the option to print
Imports iTextSharp.text.pdf
Imports iTextSharp.text.pdf.PdfStamper
Private Sub Submit1_ServerClick(sender As Object, e As EventArgs) Handles Submit1.ServerClick
Dim NombrePdfEntrada As String = System.IO.Path.GetFileName(File1.PostedFile.FileName) ' obtiene nombre archivo
Dim SaveLocation As String = Server.MapPath("Pdf") & "\" & NombrePdfEntrada ' obtiene ruta donde se guardara
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
File1.PostedFile.SaveAs(SaveLocation)
Dim ArchivoCargado As New PdfReader(SaveLocation)
Dim rutasalida As New FileStream(Server.MapPath("Pdf") & "\Nuevo" & NombrePdfEntrada, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
Dim stampArchivoOutput As New PdfStamper(ArchivoCargado, rutasalida)
Dim passdue As String = ""
Dim arraydueño() As Byte = System.Text.Encoding.ASCII.GetBytes(passdue)
Dim passinv As String = ""
Dim arrayinvitado() As Byte = System.Text.Encoding.ASCII.GetBytes(passinv)
stampArchivoOutput.SetEncryption(False, passdue, passinv, PdfWriter.ALLOW_PRINTING)
stampArchivoOutput.Close()
ArchivoCargado.Close()
Response.Write("El archivo ha sido cargado.")
Catch Exc As Exception
Response.Write("Error: " & Exc.Message & Exc.HelpLink
)
End Try
Else
Response.Write("Seleccione un archivo para cargar.")
End If
End Sub
End Class
Stupid question!
I'm checking if the inputboxes are empty...but after the check, I want to navigate back to my form and give the user a second chance to change their input.
At this moment, the app will show a messagebox if it's empty, but he goes further in my code to the second check...is there a code where I can break the code an go back to the form?
My code:
If naam = "" Then
MessageBox.Show("Naam mag niet leeg zijn", "No entry",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
prijsstr = TextBox2.Text
If prijsstr = "" Then
MsgBox("Prijs mag niet leeg zijn")
ElseIf IsNumeric(prijsstr) = False Then
MsgBox("Prijs moet numeriek zijn")
Else
prijs = Integer.Parse(prijsstr)
End If
If prijs < 0 Then
MsgBox("Prijs mag niet onder 0 zijn")
End If
Couldn't you just Return?
If naam = "" Then
MessageBox.Show("Naam mag niet leeg zijn", "No entry",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
prijsstr = TextBox2.Text
If prijsstr = "" Then
MsgBox("Prijs mag niet leeg zijn")
Return
ElseIf IsNumeric(prijsstr) = False Then
MsgBox("Prijs moet numeriek zijn")
Return
Else
prijs = Integer.Parse(prijsstr)
End If
If prijs < 0 Then
MsgBox("Prijs mag niet onder 0 zijn")
Return
End If
I will be very grateful for your help on this.
I am trying to populate a treeview to show only a directory as its main root and its sub directories. Other codes and tutorials online show drives and other special folders.
I wan to show only a folder path like:
C:\Main Folder\Subdirectory1\Subdirectory2 etc. in the nodes
This is all I have and its not helping.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs)
'Get a list of drives
Dim drives As DriveInfo() = DriveInfo.GetDrives()
Dim rootDir As String = String.Empty
'Now loop thru each drive and populate the treeview
For i As Integer = 0 To drives.Length - 1
rootDir = drives(i).Name
'Add this drive as a root node
TreeView1.Nodes.Add(rootDir)
'Populate this root node
PopulateTreeView(rootDir, TreeView1.Nodes(i))
Next
End Sub
Private Sub PopulateTreeView(dir As String, parentNode As TreeNode)
Dim folder As String = String.Empty
Try
Dim folders As String() = System.IO.Directory.GetDirectories(dir)
If folders.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each folder_loopVariable As String In folders
folder = folder_loopVariable
childNode = New TreeNode(folder)
childNode.Nodes.Add("")
parentNode.Nodes.Add(childNode)
Next
End If
Dim files As String() = System.IO.Directory.GetFiles(dir)
If files.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each file As String In files
childNode = New TreeNode(file)
parentNode.Nodes.Add(childNode)
Next
End If
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add(folder & Convert.ToString(": Access Denied"))
End Try
End Sub
He tomado como base tu código y he hecho algunas modificaciones para poder adaptarlo a mis necesidades.
Si necesitas crear una lista de todos los archivos por unidades, la funcion ActualizaTV es la encargada de Actualizar el TreeView que, en mi caso, se llama tvDir
Te dejo el resultado por si te viene bien:
Sub ActualizaTV(workpath As String)
If workpath Is Nothing Then Exit Sub
With tvDir
.Nodes.Clear()
'Creating the root node
.Nodes.Add(New TreeNode(workpath))
PopulateTreeView(workpath, .Nodes(0))
End With
End Sub
Sub PopulateTreeView(dir As String, parentNode As TreeNode)
Try
'Se añada en primer lugar los archivos del directorio
For Each file In System.IO.Directory.GetFiles(dir)
If file.Length = 0 Then Continue For
parentNode.Nodes.Add(New TreeNode(file.Replace(dir & "\", "")))
Next
'Se buscan las posibles carpetas nuevas del directorio y se añadem
For Each folder As String In System.IO.Directory.GetDirectories(dir)
If folder.Length = 0 Then Continue For
parentNode.Nodes.Add(New TreeNode(folder))
'En caso de que haya subcarpetas, se repite la operación
If UBound(System.IO.Directory.GetDirectories(folder)) > 0 Or _
UBound(System.IO.Directory.GetFiles(folder)) > 0 Then _
PopulateTreeView(folder, parentNode.LastNode)
Next
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add(dir & Convert.ToString(": Access Denied"))
End Try
End Sub
Un saludo
I think the title says it all. I can send emails using outlook but now we switched to Gmail and lost all of our notification functionality in our databases.
Yes, you can send mails from Access using gmail accounts. You need CDO library-reference. Search for it ("cdo"+"access"+"send" "mail")
Then, you send them with a function like this (comments in spanish):
Function Enviar_Mail_CDO(Para As String, _
De As String, _
Asunto As String, _
Mensaje As String, _
Usuario As String, _
Password As String, _
Optional Path_Adjunto As String) As Boolean
'Me.MousePointer = vbHourglass
' Variable de objeto Cdo.Message
Dim Obj_Email As CDO.Message
Dim SerVidor_SMTP As String
Dim Puerto As String
Dim Usar_Autentificacion As Boolean
Dim usar_ssl As Boolean
SerVidor_SMTP = "smtp.gmail.com"
Puerto = "465"
Usar_Autentificacion = True
usar_ssl = True
' Crea un Nuevo objeto CDO.Message
Set Obj_Email = New CDO.Message
' Indica el servidor Smtp para poder enviar el Mail ( puede ser el nombre _
del servidor o su dirección IP )
Obj_Email.Configuration.Fields(cdoSMTPServer) = SerVidor_SMTP
Obj_Email.Configuration.Fields(cdoSendUsingMethod) = 2
' Puerto. Por defecto se usa el puerto 25, en el caso de Gmail se usan los puertos _
465 o el puerto 587 ( este último me dio error )
Obj_Email.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = CLng(Puerto)
' Indica el tipo de autentificación con el servidor de correo _
El valor 0 no requiere autentificarse, el valor 1 es con autentificación
Obj_Email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/" & _
"configuration/smtpauthenticate") = Abs(Usar_Autentificacion)
' Tiempo máximo de espera en segundos para la conexión
Obj_Email.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30
' Configura las opciones para el login en el SMTP
If Usar_Autentificacion Then
' Id de usuario del servidor Smtp ( en el caso de gmail, debe ser la dirección de correro _
mas el #gmail.com )
Obj_Email.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = Usuario
' Password de la cuenta
Obj_Email.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = Password
' Indica si se usa SSL para el envío. En el caso de Gmail requiere que esté en True
Obj_Email.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = usar_ssl
End If
' *********************************************************************************
' Estructura del mail
'**********************************************************************************
' Dirección del Destinatario
Obj_Email.To = Para
' Dirección del remitente
Obj_Email.From = De
' Asunto del mensaje
Obj_Email.Subject = Asunto
' Cuerpo del mensaje
Obj_Email.TextBody = Mensaje
'Ruta del archivo adjunto
If Path_Adjunto <> vbNullString Then
Obj_Email.AddAttachment (Path_Adjunto)
End If
' Actualiza los datos antes de enviar
Obj_Email.Configuration.Fields.Update
On Error Resume Next
' Envía el email
Obj_Email.Send
If Err.Number = 0 Then
Enviar_Mail_CDO = True
Else
MsgBox Err.Description, vbCritical, " Error al enviar el amil "
End If
' Descarga la referencia
If Not Obj_Email Is Nothing Then
Set Obj_Email = Nothing
End If
On Error GoTo 0
'Me.MousePointer = vbNormal
End Function