Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Administrador de personalizacin
Visual Basic para
aplicaciones
versin 7.0
3/2007
Derechos de autor
los derechos de autor Manual 2007 Microsoft Corporation. Todos los derechos reservados.
Su derecho a copiar esta documentacin est limitada por la ley de derechos de autor y los trminos del contrato de licencia de software. A
medida que el titular de la licencia de software, es posible realizar un nmero razonable de copias o impresiones para su propio uso. Cmo
hacer copias, adaptaciones, compilaciones o trabajos derivados no autorizados para su distribucin comercial est prohibido y constituye
una violacin de la ley castiga.
Marcas comerciales
Microsoft, Microsoft Dynamics, ActiveX, Excel, FRx, FrontPage, IntelliSense, MapPoint, Outlook, SharePoint, Visual Basic, Visual
Studio, Windows y Windows Server son marcas registradas o marcas comerciales de Microsoft Corporation, FRx Software
Corporation o sus empresas filiales en los Estados Unidos y / o otros pases. FRx Software Corporation es una subsidiaria
propiedad de Microsoft Corporation. BIO BIO Vue y son marcas comerciales o marcas comerciales registradas de NexVue
Analytics Corporation en los Estados Unidos y / o otros pases. Los nombres de compaas y productos reales mencionados aqu
pueden ser marcas comerciales o marcas registradas - en los Estados Unidos y / o otros pases - de sus respectivos dueos. Las
compaas, organizaciones, productos, nombres de dominio, direcciones de correo electrnico, logotipos, personas, lugares, y
eventos mencionados son ficticios. Ninguna asociacin con ninguna compaa, organizacin, producto, nombre de dominio,
direccin de correo electrnico, logotipo, persona, lugar o evento se pretende ni se debe inferir.
Renuncia a la garanta
Microsoft Corporation renuncia a cualquier garanta con respecto al cdigo de ejemplo contenido en este documento,
incluyendo las garantas de comerciabilidad y adecuacin para un propsito particular.
Limitacin de responsabilidad
El contenido de este manual se proporciona nicamente con fines informativos, est sujeta a cambios sin previo aviso y no debe
interpretarse como un compromiso por parte de Microsoft Corporation. Microsoft Corporation no asume ninguna responsabilidad por
los errores o imprecisiones que puedan aparecer en este manual. Ni Microsoft Corporation ni ninguna otra persona que ha estado
involucrado en la creacin, produccin o entrega de esta documentacin ser responsable de los daos indirectos, incidentales,
especiales, ejemplares o consecuentes, incluyendo pero no limitado a, cualquier prdida de beneficios anticipados, lo que resulta de
la utilizacin de este cdigo de documentacin o de la muestra.
Acuerdo de licencia
El uso de este producto est cubierto por un acuerdo de licencia proporcionado con el producto de software. Si tienes alguna
pregunta, por favor llame al Departamento de Asistencia al Cliente al 800-456-0025 (en los Estados Unidos o Canad) o +
1-701-281-6500.
Fecha de publicacin
de marzo de de 2007
Tabla de contenido iii
Tabla de contenido
Introduccin 1
Bienvenido a Visual Basic para aplicaciones ............................................ ............ 1
Cul es en este manual? .................................................. ............................ 1
Convenciones de la documentacin ................................................ ........................ 2
propiedades 23
BlankErr Propiedad ................................................ ................................... 23
Propiedad permitido ................................................ ................................... 23
NombreCampo Propiedad ................................................ ................................ 24
La partida Propiedad ................................................ ................................... 25
Mscara Propiedad ................................................ ....................................... 26
Max Propiedad ................................................ ........................................ 27
Propiedad min ................................................ ......................................... 27
ndiceDeTabulacin Propiedad ................................................ .................................. 27
La propiedad visible ................................................ ..................................... 28
Glosario 199
ndice 201
Introduccin 1
Introduccin
Visual Basic para directrices de codificacin idioma de la aplicacin de Microsoft Dynamics SL.
Una lista completa de Microsoft Dynamics SL referencias de interfaz de programacin de aplicaciones (API).
Se utiliza para complementar el Visual Basic para aplicaciones de productos disponibles en el mdulo de personalizacin Manager,
este manual se divide en las siguientes secciones:
propiedades
Describe y proporciona ejemplos de los eventos de pantalla VBA. Estos se componen de diversos controles de ventana y
objetos.
Describe y proporciona ejemplos de funciones de API de Microsoft Dynamics SL disponibles en el lenguaje Visual Basic para
Aplicaciones.
Glosario
Define palabras comnmente usadas VBA y terminologa.
2 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Convenciones de la documentacin
Las siguientes convenciones se usan en este documento:
eleccin requerida para una Una lista entre llaves, con operador OR (|) separar opciones: {Goto etiqueta | Resume
discusin de una lista de opciones
Next | Goto 0}
Programacin VBA en Microsoft Dynamics SL 3
Microsoft Visual Basic para Aplicaciones (VBA) es una tecnologa de desarrollo integrado que le ayudar a personalizar
aplicaciones de software empaquetado e integrarlos con los datos y sistemas existentes. VBA ofrece un conjunto completo de
herramientas de programacin basado en el sistema de desarrollo de Microsoft Visual Basic.
Con Microsoft VBA, puede maximizar las capacidades del mdulo de personalizacin Manager para crear personalizaciones que
satisfacer incluso las ms exigentes necesidades de negocio de forma rpida y rentable. El uso de VBA y personalizacin Manager para
personalizar Microsoft Dynamics SL en lugar de aplicaciones en desarrollo desde el principio le ayudar a ahorrar tiempo y dinero, reducir
los riesgos, conocimientos de desarrollador de apalancamiento, y producir el exacto soluciones de software necesarios para sus
necesidades empresariales nicas.
Caractersticas principales
Estandarizada entorno de desarrollo integrado (IDE) - Un IDE estndar de la industria que incluye el Editor de Visual Basic,
que es familiar para los desarrolladores de software en todo el mundo
paridad-lengua de la base total con Microsoft Visual Basic - Las mismas mejoras del lenguaje bsico como
herramienta de desarrollo rpido de aplicaciones de Microsoft
IDE localizada y ayuda en lnea - Soporte para los desarrolladores que trabajan en idiomas distintos del Ingls
microsoft IntelliSense La tecnologa - referencia inmediata a la sintaxis de Microsoft Dynamics SL activos y de asistencia inmediata
con el modelo de objetos
formularios de Microsoft - La capacidad de crear formas ricas y cuadros de dilogo personalizado en cualquier aplicacin de Microsoft Dynamics
SL
ActiveX compatibles con los controles - Insertar controles ActiveX directamente en formularios de Microsoft
4 Personalizacin Reference Manager de Visual Basic para Aplicaciones
VBA en aplicaciones externas como otros desarrolladores de aplicaciones compatibles con COM Microsoft Office o puede escribir
pequeas cantidades de cdigo de programa para controlar el comportamiento de los objetos de imagen de Microsoft Dynamics SL. Estos objetos
pueden ser controlados desde el interior de VBA y personalizacin Manager, as como de cualquier herramienta externa compatible con COM.
Editor de cdigo
El Editor de Visual Basic incluye un editor de cdigo (Figura 1) que proporciona la sintaxis con cdigo de color, caractersticas de IntelliSense,
cdigo de arrastrar y soltar, comentario de bloque y uncomment, y comprobacin de sintaxis.
Los desarrolladores pueden abrir ventanas de cdigo para cualquier objeto que admite el cdigo detrs de l (una pantalla de Microsoft
Dynamics SL, por ejemplo), as como mdulos, clases, o las formas aadido al proyecto de VBA. En cada ventana, caractersticas de
IntelliSense (Figura 2) proporcionan la sintaxis de la marcha y la asistencia de programacin:
Palabra completa - completa la palabra est tecleando cuando suficientes cartas se han escrito para que la palabra distinta
Informacin rpida - Una punta de proporcionar informacin de sintaxis que aparece automticamente cuando se escribe un nombre de procedimiento o
mtodo
Propiedades de la lista / Mtodos - un men con las propiedades y mtodos disponibles para un objeto que precede a un perodo
en la sintaxis (.)
Constantes de Usuarios - Un men con constantes vlidas para la propiedad o argumento que se accede
DataTips - La informacin que aparece cuando VBA est en modo de interrupcin; muestra el valor de una variable debajo
del cursor
El Editor de cdigo tambin permite a los desarrolladores especificar indicadores de margen para establecer un punto de interrupcin, establezca la siguiente
instruccin, o establecer un marcador, simplemente haciendo clic en el margen de la ventana Editor de cdigo (figura
3).
poderosas herramientas de depuracin del IDE VBA, los mismos que estn disponibles para los desarrolladores de Visual Basic, permiten a los desarrolladores
identificar rpidamente compilacin, la lgica del programa, y el tiempo de ejecucin de errores. Estas herramientas incluyen:
Los locales Ventana - Mostrar automticamente todos los valores de las variables actualmente en su alcance
Relojes Ventana - Permisos de valores de la variable o expresin especfica de monitoreo; Permisos de interrupcin de la ejecucin
de cdigo basado en el estado del valor de expresin de inspeccin
Pila de llamadas - Muestra los procedimientos y las llamadas activas durante el modo de pausa
Para mejorar la eficiencia de depuracin de cdigo, los desarrolladores pueden arrastrar y soltar cdigo del Editor de Visual Basic en el Inmediato
y Los locales ventanas.
Examinador de objetos
Clave para el desarrollo de Microsoft Dynamics SL eficiente es la capacidad de manipular objetos de aplicaciones y componentes rpidamente.
La IDE ofrece a los desarrolladores esta capacidad con su Examinador de objetos que diferencia con precisin entre propiedades integradas,
propiedades personalizadas, mtodos, controladores de eventos, y procedimientos definidos por el usuario (Figura 6).
El Examinador de objetos tambin muestra los tipos de funcin de retorno, nombres de parmetros y tipos, y los tipos y las constantes definidas por el
usuario. Hipervnculo hace referencia salta a objetos permiten una fcil navegacin de la jerarqua de objetos. Los desarrolladores tambin pueden
utilizar el Examinador de objetos para buscar objetos y miembros a travs de las bibliotecas de tipos.
Debido a formularios de usuario se pueden mostrar modal, los usuarios pueden interactuar con una aplicacin de Microsoft Dynamics SL mientras
se muestra el cuadro de dilogo.
10 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Como complemento de las formas de Microsoft es del IDE Formulario Integrado Designer. Perfectamente integrado en IDE, el diseador de la
forma proporciona un lienzo visual que permite a los desarrolladores disear elementos de la interfaz de usuario y escribir cdigo de la
aplicacin desde dentro de la misma rea de trabajo.
Desarrolladores colocan controles de dilogo en el formulario usando la caja de herramientas Controles. Una vez que los controles estn en la forma, que se
pueden mover de forma rpida, cambiar de tamao, o duplicadas de acuerdo a las necesidades de la forma. El Cuadro de controles puede ser configurado para
mostrar todos los controles del sistema registrados, o puede ser personalizado por:
Creacin de plantillas de control - control (s) Arrastre desde un formulario de nuevo a la caja de herramientas Controles para crear una plantilla de
control personalizado reutilizable.
Aadir o eliminar pginas - Aadir pginas al cuadro de controles personalizados que contienen grupos de controles de formulario.
Importacin de pginas de control - Agregar pginas importndolos de otro desarrollador. Tambin puede exportar pginas de control
para su uso por otros desarrolladores.
En complemento de apoyo
VBA es totalmente compatible con fines especiales complementos, tales como escritores de cdigo y diseadores de formularios, que:
Seguridad en el proyecto
Para proteger su propiedad intelectual y la integridad de sus personalizaciones, los desarrolladores pueden proteger con contrasea cada
proyecto de VBA.
Objetos
Un objeto es cualquier elemento utilizado en la interfaz grfica de usuario (es decir, la ventana de Microsoft Dynamics SL) para controlar la entrada
y salida de datos. Cada campo, la etiqueta o marco en una ventana de Microsoft Dynamics SL-incluso la propia ventana, se considera un objeto.
Todos los objetos tienen propiedades, atributos que determinan cmo se ve un objeto y lo que hace (por ejemplo, abrir un formulario o mostrar un
valor).
Eventos
Un evento se est produciendo una actividad dentro del entorno de ventanas en un punto en el tiempo (por ejemplo, al hacer clic en el ratn,
cuando se carga un formulario, o cuando un registro se guarda). Los eventos son tpicamente parte de las propiedades de un objeto de
Microsoft Dynamics SL. Eventos y sus tipos de objetos asociados se resumen a continuacin:
Defecto Controlar
chk Controlar
LineGotFocus Cuadrcula
LineChkEvent Cuadrcula
Carga Formar
Monitor Formar
Esconder Formar
OnFinish Actualizar
OnInsert Actualizar
OnCancel Actualizar
OnUpdate Actualizar
OnDelete Actualizar
14 Personalizacin Reference Manager de Visual Basic para Aplicaciones
API
Microsoft Dynamics SL proporciona un conjunto completo de funciones y declaraciones que son totalmente compatibles con el lenguaje VBA
de interfaz de programacin de aplicaciones (API). La realizacin de tareas que van desde la validacin de una fecha a aliasing ciertas
constantes de Microsoft Dynamics SL utilizados especficamente por el mdulo de transaccin de importacin, estas API pueden manejar casi
cualquier desarrollo que necesite su aplicacin personalizada puede tener. Las API actuales se muestran y explican en Microsoft Dynamics SL
llamadas a funciones API
Declaracin de variables
VBA es compatible con los mtodos completos de declaracin de variables. Sin embargo, en el contexto de Microsoft Dynamics SL,
debe seguir ciertas pautas especficas al declarar variables. No sea redundante en sus declaraciones de variables. La posibilidad de
declarar estos como global en lugar de DIM en cada subrutina. De esta manera, slo tendr que declarar una vez. Lugar Option
Explicit en General_Declarations as como desde el principio de los archivos externos. Esta es una funcin de Visual Basic que
asegura explcita declaracin de variables. Visual Basic y VBA tanto apoyan el uso de $,%, y # como cadena, entero, y los tipos de
variables dobles respectivamente. No es necesario establecer explcitamente los campos personalizados en "" (NULL) bajo el control
del programa. Al declarar dos variables globales, como se muestra en los ejemplos de estructura tipo, slo hay que establecer
bRecord = nrecord para anular el registro o bRecord.FieldName = nRecord.FieldName para anular un campo en particular.
Los archivos de mdulo VBTools_VBA se instalan en el directorio del programa Microsoft Dynamics SL bajo CU \ VBA \ modules. Este
directorio contiene declaraciones globales de las estructuras y las variables que se pueden utilizar en un programa de VBA. Estos se
proporcionan para que los valores de retorno para las funciones, por ejemplo, no necesita ser declarado explcitamente por el programa
VBA (SERR =, serr1 =, etc.). El mdulo VBTools_VBA tambin contiene declaraciones de las funciones y subrutinas en el kernel de
Microsoft Dynamics SL (Swimapi.dll) que pueden ser utilizados en un programa de VBA. Todas las funciones estndar de Visual Basic y
rutinas ($ formato, Trim $, etc.) las cuales estn documentadas en el Visual Basic para aplicaciones de ayuda y las funciones declaradas
explcitamente en el mdulo VBTools_VBA se pueden utilizar en un programa de VBA. Tenga en cuenta que las declaraciones de las
funciones y subrutinas en el mdulo VBTools_VBA proporcionan la sintaxis de la funcin o el uso de la subrutina. Las preguntas sobre la
sintaxis de uso de cualquier funcin de API de Microsoft Dynamics SL y las constantes especficas definidas son contestadas por
referencia mdulo VBTools_VBA o mediante el uso de la caracterstica IntelliSense de VBA.
Un archivo externo puede ser creado que contiene las funciones especficas de la aplicacin, constantes y subrutinas (en formato
de texto) y se aadi en la misma forma que el mdulo VBTools_VBA. Tambin puede crear sus propias funciones en un DLL y
declarar en la misma forma que Microsoft Dynamics SL funciones de la API en el mdulo VBTools_VBA. Si conoce el nombre del
objeto, no es necesario aadir ningn cdigo en la ventana de eventos para el objeto de Microsoft Dynamics SL. Por ejemplo, si
ha creado una rutina que desea han llamado por ccustid_Chk, puede nombrar a esta ccustid_Chk rutina. Al incluir este archivo,
esta rutina se llama automticamente. Las dos nicas excepciones a esto son que no se puede tener Update o Delete como un
nombre de Sub. Estas son las palabras reservadas de Visual Basic. En estos dos casos, lo que tendra que haber codificado en la
pantalla de llamar a sus rutinas externas.
Programacin VBA en Microsoft Dynamics SL 15
Niveles y Eventos
Cada vez que se inserta un nuevo campo en un formulario, se debe especificar el nivel asociado con ese campo. UN nivel identifica
la asociacin lgica de los registros y campos que son mantenidos por una aplicacin particular. Por ejemplo, el Entrada de
diario ( 01.010.00) ventana tiene dos niveles distintos: por lotes y detalle. El nivel de lote contiene los campos asociados a la
tabla de lotes, mientras que el nivel de detalle contiene campos asociados con las transacciones del Libro Mayor mesa
(GLTran). Estos niveles se numeran empezando en cero (0). Por lo tanto, es de lote Nivel 0 y Nivel 1 es Transaccin.
Estos nmeros de nivel son muy importantes cada vez que se actualiza la base de datos. El Microsoft Dynamics SL kernel inicia el
evento OnUpdate apropiado (Guardar, OnFinish, OnInsert, OnDelete) tantas veces como hay niveles para la aplicacin particular.
En el ejemplo se ha indicado anteriormente ( Entrada de diario) el evento OnUpdate apropiado realiza dos veces, una vez para el
lote (nivel 0) y una vez para el GLTran (Nivel 1) si los campos en ambos niveles requieren actualizacin / insercin.
Al colocar el cdigo de VBA al evento OnUpdate, debe determinar el nmero de nivel que desea asociar el cdigo. Por lo
general, la colocacin de una caja de Seleccionar nivel al comienzo del evento apropiado lleva a cabo esto. Por ejemplo,
el cdigo siguiente en 01,010 ejecuta en el nivel apropiado en el caso OnUpdate:
End Select
Funciones de mensajes
Hay varias funciones de aviso de que un programa de VBA puede hacer referencia. El uso de estas funciones elimina la necesidad de
declarar variables para la celebracin de cadenas de mensajes. Por ejemplo, en la norma VB, debe declarar tres variables para la
celebracin de la cadena del mensaje, el tipo y ttulo. Se puede crear un mensaje, asignarle un msg_id y Msg_type de 1, y aadirlo a la
tabla de mensajes de Microsoft Dynamics SL. De esta manera, se puede eliminar la necesidad de declarar estas variables adicionales y
haga referencia al nmero del mensaje en la llamada declaracin de desastre. Esto tambin es muy til cuando se necesita usar el mismo
mensaje en mltiples programas o rutinas. Tenga en cuenta que tambin se puede utilizar cualquiera de los mensajes de Microsoft
Dynamics SL existentes con el tipo Msg_type = 1, siempre y cuando proporcione el nmero de mensaje apropiado y cadena de sustitucin
aplicable (s).
Asegrese de que si lo hace crear un nuevo mensaje, se asigna un nmero muy alto de modo que el desarrollo de productos de
Microsoft no prevalece en el futuro. El campo msg_id en esta tabla es un entero, por lo que puede empezar a mensajes en el rango de
30000 y, probablemente, ser seguro. Tambin puede pasar parmetros de sustitucin adicionales a los mensajes.
diecisis Personalizacin Reference Manager de Visual Basic para Aplicaciones
setdate_Click sub ()
Este ejemplo compara dos fechas. Tenga en cuenta que debe incluir el .val en los nombres de las variables en su caso:
Sub Test_Click ()
Llamar MessBox ( "Las fechas son iguales", MB_OK, "Mensaje") ElseIf serr1> 0 Then
Llame MessBox ( "invdate mayor", MB_OK, "Message") ElseIf serr1 <0, entonces
Caso 1 Llamar MessBox ( "Domingo", MB_OK "Mensaje",) Caso 2 Llamar MessBox ( "Lunes",
MB_OK "Mensaje",) Caso 3 Llamar MessBox ( "Martes", MB_OK "Mensaje",) Caso 4 Llamar MessBox
( "Mircoles", MB_OK "Mensaje",) Caso 5 Llamar MessBox ( "Jueves", MB_OK "Mensaje",) Caso 6 Llamar
MessBox ( "Friday", MB_OK "Mensaje",) Caso 7 Llamar MessBox ( "Sbado", MB_OK, "Mensaje") End
Select
Programacin VBA en Microsoft Dynamics SL 17
estructuras
Simplemente no se puede declarar una variable, emitir una sentencia SQL, y recoger el resultado de la instruccin SQL en esta
variable. Debe declarar una estructura de alguna resultados de una instruccin SQL (incluyendo las funciones de agregado). Si crea
estructuras especiales para las funciones de agregado o select-seleccione fld1 especial, fld2 de registro (no se recomienda): usted
debe incluir todos los campos en la instruccin de seleccin y cualquier campo de la restriccin no incluidos en la lista de seleccin. Por
ejemplo, la instruccin de seleccin siguiente:
Seleccionar ID de cliente, nombre, cdigo postal De Cliente Dnde ciudad = 'Findlay' y Zip = '45840'
y CurrBal> 0;
Como Fin
Al utilizar funciones de agregado de SQL que se utiliza en el segundo ejemplo anterior, debe utilizar las funciones sgroupfetch
SQL.
18 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Por defecto el campo hasta la fecha actual del sistema, el siguiente evento predeterminado debe existir:
Sub cuser1_Default (nuevovalor $, retval%)
GetSysDate (GetDate)
Sub
Este evento predeterminado debe ser obligado explcitamente a ejecutar por la siguiente (Tenga en cuenta que esto normalmente se colocara
en un evento chk anterior):
Para llevar a cabo la comprobacin de errores en este campo, coloque el siguiente en su caso chk:
Entonces
'Da invlido
Entonces
'Mes invlido
Dim sqlstr $
Sqlstr = "SELECT * FROM Cliente donde CustId =" + sparm (chkstrg) + "Orden Por
ID de cliente"
En codigo:
Tambin es posible utilizar procedimientos almacenados para ejecutar INSERT, DELETE y UPDATE con parmetros.
20 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Esta personalizacin se dise para Contabilidad General Transacciones (Journal 01.010.00) pero debera funcionar con
cualquier pantalla de rejilla para el que desea a un valor por defecto en la red con el valor en el mismo campo de la lnea
anterior.
(General) Declaraciones Global PriorValue $ Sub
Si el Nivel = 0 Entonces
continuacin
"" Entonces
End Sub
Programacin VBA en Microsoft Dynamics SL 21
En este ejemplo se utiliza Contabilidad Transacciones (Journal 01.010.00) para crear automticamente una entrada en el diario de auto-equilibrio.
Coloque Batch.User3 en la parte inferior del formulario. Esto se utiliza para almacenar la cantidad enchufe.
Dif # CreatePlug ()
FPSub (DrTotal, CrTotal, 2) = serr1 SetObjectValue ( "cuser3", Str $ (Dif)) End Sub
continuacin,
'Enchufe el Offset
Este ejemplo se acumula la cantidad total de la transaccin en cuentas por pagar Vale y entrada de ajuste ( 03.010.00) y
por defecto la cantidad de la transaccin para cada lnea a la cantidad requerida para el equilibrio del documento para
los detalles. Coloque las tres lneas siguientes en General_Declarations:
LineAmount #
propiedades
BlankErr propiedad
Determina si un valor vlido debe ser introducido o defecto para el campo.
observaciones
Un valor de True indica que el campo requiere un valor. Un valor de False indica que el campo es opcional. campos con discapacidad y / o
invisibles no deben ser obligados a menos que estn en mora automticamente con un valor vlido. Si un control est marcado como
requerido por la aplicacin, entonces no puede ser marcado como opcional usando el Administrador de personalizacin. Sin embargo, si un
control est marcado como opcional por la aplicacin, entonces puede ser marcado segn lo dispuesto por el Administrador de
personalizacin.
Para modificar el valor de la BlankErr propiedad en tiempo de ejecucin, la SetProp declaracin debe ser utilizado en lugar de modificar la
propiedad directamente en el cdigo de Visual Basic. Uso de SetProp permite al sistema seguir los cambios en los valores de propiedad a fin
de evitar conflictos con las personalizaciones.
Ver tambin
propiedad habilitado
Determina si el usuario puede modificar el contenido de la control.
observaciones
Un valor de True indica que el control est activado mientras que un valor de False hace que el control debe ser inhabilitado. Los campos
necesarios no deben ser desactivados a menos que estn en mora automticamente con un valor vlido. Para modificar el valor de la Activado
propiedad en tiempo de ejecucin, la SetProp declaracin debe ser utilizado en lugar de modificar la propiedad directamente en el cdigo de
Visual Basic. Uso de SetProp permite al sistema seguir los cambios en los valores de propiedad a fin de evitar conflictos con las
personalizaciones y / u otra de API, tales como el Modo de visualizacin declaracin.
Si un control est desactivado por la aplicacin, entonces no se puede activar mediante el Administrador de personalizacin. Sin embargo,
si un control mediante la aplicacin entonces puede ser desactivado por el Administrador de personalizacin. El valor de la Activado propiedad
puede ser reducido en tiempo de ejecucin, pero no se expandi, dependiendo del nivel en el que se realizan los cambios (Todo usuario,
un grupo de usuarios, etc.). Consulte el tema Seguridad en la documentacin de personalizacin Manager. La propiedad Enabled no
debe utilizarse en el SAFGrid controlar.
Ver tambin
NombreCampo propiedad
Facilita la unin entre el control y su variable de datos en tiempo de ejecucin de Visual Basic subyacente adecuada al
operar en conjunto con el SetAddr declaracin.
observaciones
Los datos de cada individuo de control de entrada de datos se almacena en una variable subyacente de Visual Basic. En tiempo de
ejecucin del control y su variable de almacenamiento bsico visual asociada estn unidos entre s mediante una combinacin de la Nombre
del campo propiedad del control y una llamada que corresponde a la SetAddr comunicado desde dentro Form1_Load. los Nombre
del campo propiedad contiene un valor Struct.FieldName junto con otra informacin ms detallada, como campo de desplazamiento
Valor, declarar Tipo y Longitud. Como mnimo, un valor debe introducirse en el campo Struct.FieldName. Este valor estar
normalmente en el formato bTableName.FieldName. La parte de la entrada que identifica el nombre de la tabla debe corresponder
precisamente a la cadena de nombre de la tabla literal que se pasa en una llamada correspondiente a la SetAddr declaracin. No es,
sin embargo, requiere que corresponden al nombre de una tabla real dentro de la base de datos.
El valor del campo de compensacin, declarar campos Tipo y Longitud son opcionales dependiendo de si o no el nombre de la tabla
referenciada por el Struct.FieldName es en realidad el nombre de una tabla en la base de datos. Si el Struct.FieldName hace referencia a
una tabla de base de datos y luego nadar puede acceder a informacin detallada relativa a cada campo individual contenida en el mismo
utilizando el diccionario de datos SQL. Si la referencia nombre de tabla no se corresponde con el nombre de una tabla en la base de
datos a continuacin, los valores deben ser introducidos en el campo Offset Valor, Declarar campos Tipo y Longitud.
La propiedad NombreCampo se puede modificar en tiempo de diseo nica; que no se puede modificar en tiempo de ejecucin. La siguiente
Flotador Doble 2 8
Fecha SDATE 3 4
Lgico Entero 7 2
Ver tambin
Declaracin VBA_SetAddr
propiedades 25
La partida de la propiedad
Contiene el ttulo para el columna de cuadrcula correspondiente para los controles en realidad asociados con una
SAFGrid.
observaciones
Los encabezados de columna que contienen ms de una lnea se pueden implementar mediante la separacin del texto para cada lnea con
una coma como lnea una, de dos lneas. Para modificar el valor de la Ttulo propiedad en tiempo de ejecucin, la SetProp declaracin debe
ser utilizado en lugar de modificar la propiedad directamente en el cdigo de Visual Basic. Uso de SetProp permite al sistema seguir los
cambios en los valores de propiedad a fin de evitar conflictos con las personalizaciones. Si un grupo de botones de opcin aparece dentro de
una red, la red utiliza el Ttulo propiedad del botn primera opcin como el encabezado de la columna.
Ver tambin
Mscara propiedad
Determina el tipo y el nmero de caracteres que se pueden introducir para un campo en particular.
observaciones
Cada personaje en el Mscara propiedad corresponde a un carcter en el campo visualizado. Si un carcter de mscara en particular es
uno de los tipos de mscaras compatibles, a continuacin, se permitirn los correspondientes valores vlidos para esa posicin de edicin
especial. De lo contrario, el carcter se considera que es una cadena literal que se mostrar en el campo. Estos son los literales de cadena
nica pantalla, haciendo que el cursor de forma automtica a saltar por encima de ellos durante la entrada de datos. Por otra parte, las
cadenas literales no se almacenarn en el valor resultante del campo de datos subyacente, ya que son slo para fines de visualizacin.
Para modificar el valor de la Mscara propiedad en tiempo de ejecucin, la SetProp declaracin se debe utilizar, en lugar de modificar la
propiedad directamente en el cdigo de Visual Basic. Uso de SetProp permite que el sistema para rastrear cambios en los valores de
propiedad, evitando conflictos con las personalizaciones. El valor de la Mscara propiedad puede ser reducido en tiempo de ejecucin, pero
no se expandi, dependiendo del nivel en el que se realizan los cambios (Todo usuario, un grupo de usuarios, etc.). Consulte el tema
Seguridad en la documentacin de personalizacin Manager.
9 Numrico (0-9)
Ver tambin
Declaracin SetProp
propiedades 27
Max propiedad
Determina el valor vlido mximo para el control.
observaciones
Para modificar el valor de la Max propiedad en tiempo de ejecucin, la SetProp declaracin debe ser utilizado en lugar de modificar la
propiedad directamente en el cdigo de Visual Basic. Uso de SetProp permite al sistema seguir los cambios en los valores de propiedad a
fin de evitar conflictos con las personalizaciones. El valor de la Max propiedad puede ser personalizado para un valor inferior utilizando el
Gestor de personalizacin. sin embargo, el Max propiedad no puede ser personalizado para un valor ms alto. Consulte el tema
Seguridad en la documentacin de personalizacin Manager.
Ver tambin
propiedad min
Determina el valor mnimo vlido para el control.
observaciones
Para modificar el valor de la min propiedad en tiempo de ejecucin, la SetProp declaracin debe ser utilizado en lugar de modificar la
propiedad directamente en el cdigo de Visual Basic. Uso de SetProp permite al sistema seguir los cambios en los valores de propiedad a
fin de evitar conflictos con las personalizaciones. El valor de la min propiedad puede ser personalizado para un valor ms alto mediante el
Administrador de personalizacin. sin embargo, el min propiedad no puede ser personalizado para un valor inferior. Consulte el tema
Seguridad en la documentacin de personalizacin Manager.
Ver tambin
ndiceDeTabulacin propiedad
Determina la secuencia lgica de controles dentro de su forma parental.
observaciones
Cuando el usuario presiona la tecla Tab, el orden real de progresin a travs de los controles se determina por el valor de la ndiceDeTabulacin propiedad
especificada durante la construccin del programa. Sin embargo, hay varias excepciones a esta regla general. En particular, el enfoque se omita por
el control en la siguiente secuencia de tabulacin si no est habilitado o invisible. Adems, el tiempo de diseo ndiceDeTabulacin valor de la
propiedad puede ser modificado mediante el Administrador de personalizacin. Esto permite que la secuencia lgica de entrada de datos para
cualquier pantalla en particular para ser personalizadas para circunstancias nicas. los ndiceDeTabulacin la propiedad tambin es utilizado por
llamadas a la API que hacen referencia a una serie de controles, tales como:
SetDefaults, SetProp y DispFields. Estos tipos de llamadas a la API permiten la aplicacin para especificar el primer y ltimo control sobre
la cual la operacin designada debe ser realizada. Todos los controles que tienen una ndiceDeTabulacin Entre los ndiceDeTabulacin del
primer control y el ndiceDeTabulacin del ltimo control sern incluidos en el grupo de controles especficos.
Esta propiedad se puede modificar en tiempo de diseo nica; que no se puede modificar en tiempo de ejecucin.
Ver tambin
La propiedad visible
Determina si el control es visible.
observaciones
Un valor de True indica que el control es visible mientras que un valor de False hace que el control sea invisible.
Los campos necesarios no se deben hacer invisible a menos que estn en mora automticamente con un valor vlido.
Para modificar el valor de la Visible propiedad en tiempo de ejecucin, la SetProp declaracin debe ser utilizado en lugar de modificar la
propiedad directamente en el cdigo de Visual Basic. Uso de SetProp permite al sistema seguir los cambios en los valores de propiedad a
fin de evitar conflictos con las personalizaciones. Si un control se hace invisible por la aplicacin, entonces no puede hacerse visible
mediante el Administrador de personalizacin. Sin embargo, si un control se hace visible por la aplicacin, entonces se puede hacer
invisible por el Gestor de personalizacin.
Las siguientes observaciones se refieren a la forma en la propiedad visible se refiere a la SAFGrid controlar. En tiempo de ejecucin, el
programa obliga a la cuadrcula para ser visible durante la inicializacin. No establezca esta propiedad en tiempo de diseo para el SAFGrid controlar.
Del mismo modo, no llame SetProp () en un control de formulario-view porque que revela un intento de modificar la propiedad Visible en un tipo
de fila por fila de base, que no es compatible.
La nica modificacin de tiempo de ejecucin correspondiente a la visibilidad de un componente de la red es para mostrar u ocultar una
columna entera, basndose en una regla por datos. Por ejemplo, supongamos que la aplicacin A contiene una rejilla que tiene 10
campos. Supongamos tambin que los campos 7, 8, 9 y 10 no debe ser visible a menos XYZ mdulo est instalado y configurado. Por
ltimo, vamos a suponer que el Mdulo XYZ es ni instalado ni configurado. Esto significara que la aplicacin A tiene que ocultar campos
7,
8, 9 y 10. Puesto que estos campos estn asociados con una SAFGrid, nos gustara ocultar las columnas de la cuadrcula que se
corresponden con los campos 7, 8, 9 y 10. Esta operacin se puede realizar durante Form_Load llamando MSetProp () para cada uno de los
campos que se oculta - cada vez que la especificacin de un valor de False para el Visible propiedad. Tenga en cuenta que en el MSetProp () escenario,
hay que hacer esta llamada antes de el SAFGrid recibe el foco (como en la carga de la pantalla, o en una llave maestra evento Chk de un
nivel de cabecera). No llames MSetProp () desde dentro SAFGrid eventos, tales como
LineGotFocus ().
Para ocultar una SAFGrid, selecciona el Visible propiedad de la estructura subyacente a Falso.
Ver tambin
Para introducir el cdigo VBA para un objeto, seleccione V isual Basic Editor desde el do onfigurar men o botn derecho del ratn para abrir un
men (tambin se abre al pulsar + F11 Alt).
Una vez en el VBE, seleccione el objeto y el evento para el que est ingresando el cdigo VBA. A continuacin, introduzca el cdigo de VBA del
evento en la regin de texto debajo de las selecciones de objetos y eventos.
Nota: Se puede escribir rutinas de uso general que pueden ser llamados por otras rutinas o eventos en la misma pantalla
seleccionando el evento (general).
Cuando se trabaja con el VBA, es importante entender el concepto de eventos. Los eventos son simplemente acciones que tienen
lugar en un punto en el tiempo: al hacer clic en el ratn, cuando se carga el formulario, cuando se guarda un registro, al pulsar TAB
para pasar al siguiente campo en la pantalla. Se puede aadir cdigo VBA para cualquiera de los siguientes eventos:
Descripcin del
evento Evento se produce antes o despus de sucesos de la aplicacin subyacente
linechk Despus
Terminar Despus
Cancelar Despus
Sintaxis
observaciones
Cada vez que el usuario modifica el valor de un campo, el nuevo valor menudo necesita ser validado (la comprobacin de errores). Si el
nuevo valor de datos es vlido, la aplicacin puede realizar otras operaciones relacionadas, tales como re-default o desactivar otros campos.
El evento Chk es donde tal cdigo normalmente reside ya que este evento se llama cualquier momento se cambia el valor del campo. El
evento Chk tambin puede disparar en otros momentos cuando el usuario no modifica directamente el valor del control. Por ejemplo, navegar
a travs de los registros existentes en un nivel normal mediante el Primero ltimo, Anterior, y Siguiente botones de la barra es
conceptualmente equivalente al usuario que introduce nuevos valores de los campos clave para abrir diferentes registros. En consecuencia,
cuando se navega a travs de los registros existentes en un nivel normal, el evento Chk para cada campo clave en ese nivel se dispara cada
vez que el usuario se desplaza de un registro a otro, independientemente de cmo se haya realizado la operacin de navegacin (entrada de
datos o navegacin de la barra de herramientas , por ejemplo). El evento Chk tambin puede disparar en relacin con la propiedad de
disparo. Por ejemplo, usando la propiedad de activacin, una relacin entre FieldA y FieldB se puede definir de manera que FieldB se
re-validada (Chk su caso debera llamarse) cada vez que el valor de los cambios FIELDA. los chk evento utiliza los siguientes argumentos:
ndice Entero El argumento opcional dependiendo de si o no el control est asociado con una matriz de control.
Este valor se usa para identificar de forma exclusiva el control dentro de una matriz de control.
ChkStng cuerda Si el usuario acaba de teclear un nuevo valor para el campo y presiona Tab, luego ChkStrg
corresponder a ese nuevo valor de datos. Si el evento Chk se detiene por cualquier otra
razn, como la navegacin, disparadores, etc, entonces el valor de ChkStrg es el valor de
los datos que se asignar al campo subyacente menos que sea rechazado en el caso de
Chk. En este ltimo caso, es posible que el valor del campo ser la misma, por ChkStrg
reflejar este hecho.
retval entero Un valor de datos puede ser rechazada simplemente modificando el parmetro RetVal que se pasa
al evento Chk. Este parmetro es en realidad pasa por referencia lo que significa que cualquier
modificacin a RetVal se detectan automticamente por el sistema una vez que el control del
programa sale del evento Chk.
Microsoft Dynamics SL pantalla Eventos 31
La siguiente tabla muestra los posibles valores que pueden ser asignados a RetVal y su efecto correspondiente en el
sistema una vez que el control del programa sale del evento Chk:
RetVal Descripcin
NoAutoChk Suprime la comprobacin de errores automtico que normalmente se producen despus del evento Chk. Se
suele utilizar en caso de Chk de campos clave cuando el resultado de la PVChkFetch o DBNavFetch es
NOTFOUND pero el usuario todava debe ser capaz de agregar nuevos registros. Dado que este valor de
retorno est diseado para permitir ChkStrg pasar como vlida a pesar de que un elemento de datos
correspondiente no pudo ser localizado dentro de la base de datos, el valor de ChkStrg ser, por definicin, se
adopta como nuevo valor del campo en lugar de ser rechazada.
ErrNoMess Este valor de retorno es similar a un nmero de mensaje en el hecho de que har que el valor de
ChkStrg a ser rechazada. Sin embargo, el sistema no mostrar un mensaje desde la aplicacin ya
debera haberlo hecho durante el evento Chk. Esto es til en los casos en que el mensaje requiere
valores de datos para uno o ms parmetros de sustitucin. En consecuencia, la aplicacin puede
utilizar la instruccin MESSF para visualizar el mensaje junto con los valores de sustitucin requeridas y
a continuacin, establezca posteriormente RetVal = ErrNoMess.
Ejemplo 1
El siguiente ejemplo ilustra el caso de Chk, en un control de campo no clave, en el que un registro correspondiente al valor de ChkStrg
debe ser trada desde la base de datos para su uso por la aplicacin. Si el registro no se puede encontrar a continuacin, que se ha de
considerar un error. Este fragmento de cdigo fue tomada realmente del evento Chk del campo Tipo ganancias en los valores
predeterminados del parte de horas sub-pantalla de la dcada de mdulo de nmina Mantenimiento del empleado ( 02.250.00) ventana.
Esta aplicacin particular requiere que el Tipo de Ganancias por defecto para todos los empleados deben contribuir al pago neto. Por lo
tanto, no basta con que el usuario introduzca el ID de cualquier tipo de ingresos. Ms bien, que las ganancias Type debe tambin ser
definida como una contribucin al pago neto. Si el tipo relevante ganancias no contribuye al pago neto a continuacin, ser rechazada
simplemente estableciendo RetVal al nmero determinado mensaje explicando la naturaleza del problema. 260 Nmero de mensaje es el
mensaje real que se mostrar y su texto asociado en el archivo de mensajes de texto es el siguiente: Las ganancias tipo debe contribuir al
pago neto, por favor, vuelva a introducir.
Sub cDfltEarnType_Chk (chkstrg As String, retval As Integer) RetVal = PVChkFetch1 (CNULL, CSR_EarnType, chkstrg, bEarnType, LenB (bEarnType))
Si (RetVal = 0) A continuacin,
If End Sub
32 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Ejemplo 2
Sub cFieldA_Chk (chkstrg $, retval%)
"BADVALUE" Entonces
Retval% = 8033 'retorno mensaje nmero 8033: datos no vlidos. Valor End If End Sub
Microsoft Dynamics SL pantalla Eventos 33
Sintaxis
observaciones
Utilice este evento para activar acciones en respuesta a que se presiona un botn. los Hacer clic evento
ndice Entero El argumento opcional dependiendo de si o no el control est asociado con una matriz de control.
Este valor se usa para identificar de forma exclusiva el control dentro de una matriz de control.
Ejemplo
Sub Button1_Click ()
Se produce cuando una carga pantalla o nueva solicitud entidad actualiza la pantalla. Se produce cada vez que el control est siendo
cesacin de pagos y una propiedad por defecto no se ha implementado.
Sintaxis
observaciones
El valor de datos por defecto para cualquier control de entrada de datos en particular se puede especificar ya sea a travs de la propiedad por defecto o
el evento predeterminado. La propiedad por defecto se puede utilizar cuando el valor por defecto no est supeditada a ningn valor de cualquier otro
elemento de datos. Sin embargo, si la metodologa para la determinacin de un valor predeterminado vara dependiendo de las situaciones particulares,
entonces deber ser escrito para el evento predeterminado. Si una propiedad predeterminada se define a continuacin, no se utilizar el evento
predeterminado.
Dentro del evento predeterminado, refirindose directamente a la variable de Visual Basic al que est enlazado el control establece el
valor por defecto del campo relevante. Por ejemplo, si el control est enlazado a campo de cadena llamado bTableA.FieldA dentro de su
propiedad FieldName entonces dentro del evento predeterminado el valor del campo se puede defecto de tal manera como
bTableA.FieldA = StringValue. Los datos por defecto valor para un grupo de botones de SAFOption siempre se deriva del botn primera
opcin en el grupo, ya que por definicin slo un botn de opcin puede ser seleccionada dentro de cualquier grupo particular. los Defecto evento
utiliza los siguientes argumentos:
ndice Entero El argumento opcional dependiendo de si o no el control est asociado con una matriz de control.
Este valor se usa para identificar de forma exclusiva el control dentro de una matriz de control.
Valor antiguo cuerda Contiene el valor de los datos que el campo subyacente tena inmediatamente antes del evento
predeterminado. Esto es necesario debido a que el campo subyacente ya habr su valor sobrescrito
cuando el evento predeterminado se llama.
retval entero Un valor distinto de cero positivo retorno suprime an ms accin por defecto, incluyendo los valores
predeterminados de personalizacin y llamadas de activacin.
Ejemplo
Si un control (cFieldA) est enlazado a un campo de cadena llamado bTableA.FieldA dentro de su propiedad NombreCampo, a
continuacin, en el caso por defecto el valor del campo puede ser descalificado de una manera tal como bTableA.FieldA = StringValue.
Se produce durante la serie de acciones / eventos iniciados por una operacin de eliminacin.
Sintaxis
observaciones
Para entender cuando se produce el evento OnDelete, un desarrollador debe entender primero el concepto nivel ms alto de lo que se
conoce aqu como una operacin de eliminacin. La operacin se diferencia del caso en el hecho de que el evento OnDelete
comprende slo un segmento de una serie de eventos que implica una operacin de eliminacin.
Una operacin de eliminacin se inicia cuando el usuario hace clic en el Borrar botn en la barra de herramientas. La nica excepcin es
cuando el usuario elimina una lnea de detalle de una red, en cuyo caso se llama el evento LineChk.
Una operacin de eliminacin se compone de la siguiente serie de acciones y / o eventos. Si la aplicacin contiene ms de un
nivel normal, se solicita al usuario acerca de cul de los registros de los niveles normales estn siendo eliminados.
Procesamiento comenzar con el nivel que seleccione el usuario y continuar para cada nivel no de bsqueda con el fin de level0
a LEVELn.
El evento se llama OnDelete para el nivel. Si este es el primer nivel para procesar una transaccin de base de datos no se ha
iniciado todava. En consecuencia, la aplicacin debe llamar TranBeg si se necesita para llevar a cabo la actualizacin de base
de datos / eliminar operaciones durante el primer paso a travs del evento OnDelete.
Si la aplicacin no modific el valor de RetVal en la etapa precedente a continuacin, se elimina la tabla maestra para el
nivel. La tabla maestra para cualquier nivel particular es la tabla identificada por la llamada VBA_SetAddr para ese nivel
particular.
Una vez que todos los niveles que previamente haban sido modificados se han actualizado correctamente, la transaccin de base de
datos se termin y una nueva operacin se inicia automticamente para preparar la solicitud de ingreso de datos.
Si se produce algn error durante la eliminacin de cualquier nivel, entonces toda la operacin se aborta, incluyendo la transaccin de base
de datos. los OnDelete evento utiliza los siguientes argumentos:
retval entero La eliminacin automtica de la tabla maestra para el nivel actual, que se produce despus del evento
OnDelete para ese nivel en particular, se puede suprimir mediante el establecimiento de RetVal a la
constante simblica noaction definida en el mdulo VBTools_VBA. toda la operacin de eliminacin se
puede interrumpir mediante el establecimiento de RetVal ya sea para un nmero de mensaje o la
constante simblica ErrNoMess definida en el mdulo VBTools_VBA.
36 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Sintaxis
observaciones
flujo del evento PV procesar el nivel macro ms alta (self, 500) primero seguido por cada nivel macro inferior hasta que el parmetro de
accin se ha establecido para algo que no sea el valor por defecto (sin accin). Si se han realizado todas las llamadas macro y la accin
por defecto sigue estando ajustado entonces el dilogo de la aplicacin PV subyacente se llama (si existe).
Si el evento PV pasa un valor de nuevo otro entonces los valores aceptados un mensaje de error se producir y el evento ser
tratada como un valor de no accin.
El evento PV se utiliza para configurar el valor de slo el campo. No comprueba el campo de validez. Eso ocurrir despus en eventos
de revisin del campo (para cada nivel correspondiente). Este evento est destinado a permitir Personalizadores para desarrollar
dilogos de consulta. los PV evento utiliza los siguientes argumentos:
ndice El argumento opcional nmero entero dependiendo de si el control est asociado con
una matriz de control. Este valor se usa para identificar de forma exclusiva el control dentro de una matriz de control.
ValorDelCampo cuerda Este parmetro tiene el valor de cadena campo actual cuando llama y se utiliza como el valor aceptado el
resultado es error de comprobacin antes de aplicar al campo (control).
Accin nmero entero Este parmetro se utiliza para mantener la accin a tomar despus del evento PV fue
llamado. Por defecto, la accin es continuar con los dilogos de procesamiento fotovoltaicos. Las otras dos acciones
son Aceptar y Cancelar.
RetVal Descripcin
Aceptar Indica que no hay procesamiento de eventos PV ms se llevar a cabo y el valor de cadena campo se utilizar en la
comprobacin de errores. Si la comprobacin de errores acepta el valor a continuacin, centrarse pasarn al siguiente campo
(especificado en la lgica de comprobacin de errores).
Cancelar Indica que el dilogo ha sido cancelado y el foco est a la izquierda en el campo de llamada (control). No se
produce un procesamiento adicional.
Ejemplo
PVAction mundial como nmero entero Sub cFieldA_PV (fieldstrg
$,% de accin)
'Opciones de instalacin en cuadro combinado sub-forma que el usuario puede elegir PV. Llamar SetProp ( "cPvListCombo",
"Lista", "A; Cuenta de Activos, E; cuenta de gastos, L; cuenta de pasivo")
'Si el botn Aceptar se presion en el sub-formulario y luego fue PVAction configurados para aceptar
Entonces
"7200" Else
End If
Terminara si
action = PVAction
End Sub
38 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Se produce durante la serie de acciones / eventos iniciados por una operacin de almacenamiento.
Sintaxis
observaciones
Para entender cuando se produce el evento OnUpdate, un desarrollador debe entender primero el concepto nivel ms alto de lo que
se conoce aqu como una operacin de almacenamiento. La operacin se diferencia del caso en el hecho de que el evento OnUpdate
comprende slo un segmento de una serie de eventos que implican una operacin SAVE.
Cuando el usuario responde S en respuesta al Desea guardar los cambios pendientes? Del sistema. Este
mensaje se produce cada vez que el usuario ha modificado los datos y luego intenta introducir un nuevo
elemento, vaya a un elemento diferente o cerrar la pantalla sin guardar sus / sus cambios.
Una operacin SAVE se compone de la siguiente serie de acciones y / o eventos para cada nivel que se ha cambiado con el
fin de level0 a LEVELn. Por ejemplo, si la nica informacin que cambi reside en level0 entonces slo level0 ser procesado
durante la operacin de almacenamiento. Una transaccin de base de datos se inicia antes de que se procesan los niveles. El
evento se llama OnUpdate para el nivel.
Nota: TranEnd debe Nunca ser llamado por la aplicacin dentro del evento OnUpdate ya que el sistema ser entonces incapaz
de hacer retroceder toda la operacin SAVE.
Si la aplicacin no modific el valor de RetVal en la etapa anterior a continuacin, la tabla maestra para el nivel se actualiza.
La tabla maestra para cualquier nivel particular es la tabla identificada por la llamada VBA_SetAddr para ese nivel particular.
Una vez que todos los niveles que previamente haban sido modificados se han actualizado correctamente, la transaccin de base de
datos se termin. El evento OnUpdate entonces se llama una vez adicional. El parmetro de nivel tendr un valor correspondiente a la
constante simblica final definida en el mdulo VBTools_VBA. En este punto el nivel de status para todos los niveles debe tener un
valor de NOTCHANGED. Adems, el estado de la lnea de cada lnea de detalle individual dentro de cualquier rejillas tambin debe
tener un valor de NOTCHANGED.
Si se produce algn error durante la actualizacin de cualquier nivel, entonces toda la operacin se aborta, incluyendo la
transaccin de base de datos. los OnUpdate evento utiliza los siguientes argumentos:
InsertFlg entero True indica que vaya a insertar un nuevo registro. False indica que un registro existente est
siendo actualizado.
LevelsLeft entero Nmero de plantas an para ser procesado en el contexto de la operacin actual SAVE.
Este conteo no incluye el pase Terminado el evento a travs OnUpdate.
retval entero La actualizacin automtica de la tabla maestra para el nivel actual, que se produce despus del evento
OnUpdate para ese nivel en particular, se puede suprimir mediante el establecimiento de RetVal a la
constante simblica noaction definida en el mdulo VBTools_VBA. Toda la operacin de almacenamiento
se puede interrumpir mediante el establecimiento de RetVal ya sea para un nmero de mensaje o la
constante simblica ErrNoMess definida en el mdulo VBTools_VBA.
Ejemplo
GridHandle Global%
Dim MaintFlag%
Si el Nivel = 0 Entonces
'Se hace llamar de manera que si se realiza algn cambio que afectara a la moneda de rejilla,
Sintaxis
observaciones
Este evento se produce despus de que se visualiza un formulario de pantalla de la aplicacin (pintado en la pantalla).
Nota: Al crear procedimientos para eventos relacionados, como Activar, GotFocus, pintura y cambio de tamao, asegrese de que
sus acciones no entren en conflicto y que no causan acontecimientos recursivas.
Ejemplo
GridHandle Mundial Sub
Form1_Display% ()
Sintaxis
observaciones
Este evento se produce despus de un formulario de pantalla de la aplicacin est oculta (ya no se muestra).
Nota: Al crear procedimientos para eventos relacionados, como Activar, GotFocus, pintura y cambio de tamao, asegrese de que
sus acciones no entren en conflicto y que no causan acontecimientos recursivas.
Microsoft Dynamics SL pantalla Eventos 41
Sintaxis
observaciones
Este evento se produce para todas las formas de una aplicacin, mientras que la pantalla est cargando.
Nota: Al crear procedimientos para eventos relacionados, como Activar, GotFocus, pintura y cambio de tamao, asegrese de que
sus acciones no entren en conflicto y que no causan acontecimientos recursivas.
Ejemplo
Form1_Load sub ()
'Asignar memoria intermedia y el cursor de tabla personalizada que contiene adicional campos.
Sintaxis
observaciones
En cualquier momento el usuario inserta, actualiza o suprime una lnea de detalle en un control SAFGrid, se activa el evento LineChk. Durante
situaciones de insercin y actualizacin, el evento no se ejecuta hasta que el usuario realmente sale de la lnea de detalle.
Este evento es la ms utilizada para realizar la lgica de eliminacin especial para lneas de detalle que el usuario est intentando eliminar.
Por ejemplo, el Plan General Ledger de pantalla Cuentas de mantenimiento contiene una cuadrcula que muestra todos los registros de la
tabla de cuentas. Los usuarios pueden borrar registros de cuenta siempre que el nmero de cuenta correspondiente no se utiliza en las
pantallas de configuracin entre otras reas. Esto se aplica realmente a travs del uso de la lgica dentro del evento LineChk. Los registros
borrados se copian de la matriz de memoria subyacente a un temporal de registros suprimidos matriz de memoria. El identificador de
recurso a esa matriz de memoria se puede obtener usando la funcin MGetDelHandle. los LineChk evento utiliza los siguientes
argumentos:
RetVal La aplicacin de enteros puede evitar eliminaciones de registro, simplemente definiendo a RetVal
o bien un nmero de mensaje vlido o la constante simblica ErrNoMess definida en el mdulo
VBTools_VBA.
El mdulo VBTools_VBA contiene las siguientes constantes simblicas que definen los posibles valores de accin:
RetVal Descripcin
ABANDONADO Una lnea de detalle existentes nunca fue creado y est siendo abandonado.
El mdulo VBTools_VBA contiene las siguientes constantes simblicas que definen valores posibles RecMaintFlg:
RetVal Descripcin
newRow Indica que el usuario empieza la insercin de una nueva lnea de detalle. El estado de la lnea de detalle
se cambiar a insertar a continuacin todos los campos han sido verificado error y no se producen
errores durante el evento LineChk.
INSERTADO La actual lnea de detalle se ha aadido correctamente despus de la rejilla fue cargado y no se ha guardado
en la base de datos.
Microsoft Dynamics SL pantalla Eventos 43
RetVal Descripcin
ACTUALIZADO La lnea de detalle actual se carg inicialmente a la red, pero ha sido modificado posteriormente.
Por otra parte, las modificaciones a la lnea de detalle actual an no se han guardado.
SIN CAMBIO La lnea de detalle actual se carg inicialmente en la red y no ha sido modificado posteriormente. Nota: Registros
marcados como insertado y actualizada se les asignar automticamente el estado NOTCHANGED
despus de la prxima exitosa operacin de almacenamiento.
Ejemplo
Spread1_LineChk sub (% de accin, maintflg%, retval%)
Doble
Sub
44 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Se produce cada vez que una lnea de detalle dentro de un control de cuadrcula recibe el foco.
Sintaxis
observaciones
Cada vez que el usuario mueve o inserta una lnea de detalle dentro de un control de cuadrcula, el evento LineGotFocus se llama
inmediatamente.
El parmetro RecMaintFlg posteriormente puede ser evaluada para determinar si o no el usuario est realmente agregando una nueva
lnea de detalle. En tal caso, los valores por defecto se pueden asignar de forma explcita a los campos dentro del registro de detalle para
el cual existe ningn control correspondiente. Por ejemplo, supongamos TableA es una tabla de cabecera y TableB es un registro de
detalle. En este caso, cada registro TableA nica podra tener muchos registros TableB nicos que aparecen dentro de la SAFGrid. Sin
embargo, el principal punto de hacer aqu es que el primer segmento de la clave nica para TableB tendra que incluir un campo que se
relaciona directamente con la Tabla A (el campo de unin). Este tipo de campo es el principal candidato a ser descalificado en caso
LineGotFocus ya que siempre tendr el mismo valor (por ejemplo, el valor de TableA.KeyField). Por lo tanto, la creacin de un control
invisible con una propiedad por defecto no es realmente necesario. los LineGotFocus evento utiliza los siguientes argumentos:
RetVal integer La aplicacin puede prevenir todos los correspondientes controles de nivel de detalle
de ser incumplido automticamente cuando un nuevo registro est siendo insertado simplemente fijando
RetVal a noaction (que es una constante simblica definida en el mdulo VBTools_VBA).
El mdulo VBTools_VBA contiene las siguientes constantes simblicas que definen valores posibles RecMaintFlg:
RetVal Descripcin
newRow Indica que el usuario empieza la insercin de una nueva lnea de detalle. El estado de la lnea de detalle
se cambiar a insertar a continuacin todos los campos han sido verificado error y no se producen
errores durante el evento LineChk.
INSERTADO La actual lnea de detalle se ha aadido correctamente despus de la rejilla fue cargado y no se ha guardado
en la base de datos.
ACTUALIZADO La lnea de detalle actual se carg inicialmente a la red, pero ha sido modificado posteriormente.
Por otra parte, las modificaciones a la lnea de detalle actual an no se han guardado.
SIN CAMBIO La lnea de detalle actual se carg inicialmente en la red y no ha sido modificado posteriormente. Nota: Registros
marcados como insertado y actualizada se les asignar automticamente el estado NOTCHANGED
despus de la prxima exitosa operacin de almacenamiento.
Microsoft Dynamics SL pantalla Eventos 45
Ejemplo 1
Este ejemplo est tomado de la dcada de mdulo de nmina Las ganancias Tipo Mantenimiento ( 02.270.00) ventana. Esta pantalla es un
encabezado / Tipo de detalle de la pantalla que tiene la tabla EarnType como la tabla de cabecera y dos registros de detalle de la rejilla de
ValEarnDed y la deduccin. ValEarnDed es la tabla maestra para el nivel de detalle y la mesa Deduccin solamente se uni en una descripcin.
Tenga en cuenta que la prueba para newRow y el trabajo correspondiente solamente se llevan a cabo para las nuevas lneas de detalle.
Ejemplo 2
Spread1_LineGotFocus sub (% de accin, maintflg%, retval%)
Si maintflg% = newRow Entonces
'Por defecto campo de la lnea actual. Dim
ValorDelCampo As String * 20
Llamar GetBufferValue ( "bTableA.FieldA", ValorDelCampo) Llamada SetBufferValue (
"bTableB.FieldA", ValorDelCampo) End If End Sub
46 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Se produce cuando el usuario hace clic en el Cancelar botn en la barra de herramientas o presiona las Esc llave.
Sintaxis
observaciones
Cuando el usuario hace clic en el Cancelar botn en la barra de herramientas, el evento OnCancel se llama una vez para cada nivel con el
fin de level0 a LEVELn.
Este evento se utiliza normalmente en aplicaciones individuales de nivel constante, tales como pantallas de configuracin. Este tipo de
aplicaciones no tienen campos clave que se pueden volver a ejecutar con el fin de volver a buscar la informacin que se muestra actualmente.
En consecuencia, el evento OnCancel proporciona a la aplicacin una oportunidad para volver a buscar el registro de nivel constante (por
ejemplo, el registro de configuracin). los OnCancel evento utiliza los siguientes argumentos:
retval entero El mensaje correspondiente se mostrar si RetVal se modifica para otra cosa que no
sea la constante simblica ErrNoMess definida en el mdulo VBTools_VBA.
Ejemplo 1
El siguiente fragmento de cdigo se toma de la nmina Mantenimiento del empleado ( 02.250.00) pantalla.
'Inicializar bPRSetup
Si (PRSetup_Fetch = 0) A continuacin,
Ms
Terminara si
End Sub
Microsoft Dynamics SL pantalla Eventos 47
Ejemplo 2
GridHandle Global%
'Cambiar para no cambiado desde fuera anulacin cambia de estado de llamada SetLevelChg (Nivel 0,
NOTCHANGED)
displaygrid
End Sub
48 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Se produce cuando un usuario indica que se acaban con la informacin que se muestra actualmente en la pantalla.
Sintaxis
observaciones
El evento OnFinish se llama cuando el usuario ha terminado con la informacin que se muestra actualmente a fin de permitir la
aplicacin de una oportunidad para realizar operaciones especficas en o relacionados con los datos antes de que sale de la
pantalla del usuario. Por ejemplo, supongamos que el usuario acaba de introducir algn tipo de informacin financiera y ahora l /
ella simplemente va a cerrar la aplicacin, ya que han completado su tarea original. En ese momento, la aplicacin podra avisar al
usuario de que la informacin est fuera de equilibrio y preguntar si desean o no para remediar el problema. Sin tal advertencia, el
usuario no puede notar el error hasta que posteriormente provoca algn otro problema.
el usuario se considera terminado con la informacin mostrada en ese momento cuando se realiza cualquiera de las siguientes
operaciones:
Cuando el usuario hace clic en el Terminar botn en la barra de herramientas. En este caso, el evento OnFinish realidad dispara despus del
evento OnUpdate si una operacin de almacenamiento es necesario (por ejemplo, si alguna informacin ha cambiado).
Cuando el usuario intenta introducir un elemento nuevo, vaya a un elemento diferente o cerrar la pantalla. Si se ha cambiado
informacin, el usuario primero se le pedir que guarde sus cambios pendientes. Si no hay informacin se ha cambiado, la
pantalla se actualizar con la informacin tal como existe en la base de datos para que los datos exactos es fcilmente
disponible cuando el evento se llama OnFinish.
El evento OnFinish se llama una vez para cada nivel con el fin de LEVELn a level0. Observe que este evento se llama en el
orden inverso en comparacin con los eventos newlevel, OnUpdate, onDelete y OnCancel. Esta orden inverso permite que la
aplicacin para informar de problemas con los datos en el nivel ms granular primero.
La aplicacin puede abortar el evento OnFinish simplemente cambiando el parmetro RetVal. En este caso, tambin se aborta la
accin de los usuarios. Por ejemplo, supongamos que el usuario tiene RECORD en la pantalla y luego hace clic en el Siguiente botn
en la barra de herramientas. Esto indica que el usuario ha terminado de ver RECORD y ahora quiere ver el siguiente registro,
presumiblemente RecordB. En consecuencia, el evento OnFinish se llama justo antes de navegar a RecordB. Si la aplicacin
establece RetVal, decir a un nmero de mensaje, el mensaje correspondiente se mostrar cuando se abortar el evento OnFinish
hacia las salidas nivel actual y el funcionamiento de navegar. Dado que se abort la operacin de navegacin, el usuario ser capaz
de ver RECORD. los OnFinish evento utiliza los siguientes argumentos:
Nivel entero Nivel actual est procesando. El evento se llama OnFinish comenzando con LEVELn (el
ltimo nivel en la pantalla) y contando hacia atrs a level0.
retval entero El evento OnFinish puede ser abortado, simplemente definiendo RetVal a cualquiera de un nmero de
mensaje vlido o la constante simblica ErrNoMess definida en el mdulo VBTools_VBA.
Microsoft Dynamics SL pantalla Eventos 49
Se produce durante la serie de acciones / eventos iniciados por una operacin de insercin.
Sintaxis
observaciones
Para entender cuando se produce el evento newlevel, un desarrollador debe entender primero el concepto nivel ms alto de lo que
se conoce aqu como una operacin de insercin. La operacin se diferencia del caso en el hecho de que el evento newlevel
comprende slo un segmento de una serie de eventos que implica una operacin de insercin.
Cuando el usuario hace clic en el Terminar botn en la barra de herramientas. En este caso, el evento newlevel realidad dispara
despus de la OnUpdate y eventos OnFinish completan con xito.
Cuando el usuario hace clic en el Borrar botn en la barra de herramientas. Despus de que el registro se ha eliminado correctamente en
caso OnDelete, la aplicacin se prepara para recibir nueva informacin de forma automtica mediante el inicio de una operacin de
insercin.
Cuando el usuario navega o bien antes del primer registro o all del ltimo registro en una tabla utilizando el Anterior o Siguiente botones
de la barra de herramientas.
Cuando el usuario introduce un valor que no exista ya en la base de datos para uno o ms campos clave. Por ejemplo, si
una aplicacin contiene tres campos clave a continuacin, una operacin de insercin se iniciar si la combinacin de los
tres valores de campo clave no existe en la base de datos.
Una operacin de insercin se compone de la siguiente serie de acciones y / o eventos para cada nivel de detalle no
comenzando con el nivel en el que se inici la nueva operacin. Por ejemplo, si se inicia la operacin de insercin en level0,
los niveles sern procesados en orden desde level0 a LEVELn.
La tabla maestra para el nivel se queda en blanco. La tabla maestra para cualquier nivel particular es la tabla identificada
por la llamada VBA_SetAddr para ese nivel particular.
Desde el impago para los nuevos registros de nivel de detalle dentro de un control de cuadrcula se lleva a cabo dentro del evento
LineGotFocus, el evento newlevel no se llama a los niveles de detalle. los OnInsert evento utiliza los siguientes argumentos:
retval entero El Incumplidora automtica de todos los controles en el nivel de corriente que se produce despus
del evento newlevel para ese nivel en particular puede ser suprimida mediante el establecimiento de
RetVal a la constante simblica noaction definida en el mdulo VBTools_VBA.
50 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Ejemplo
El siguiente fragmento de cdigo se toma de la nmina Mantenimiento del empleado ( 02.250.00) pantalla.
'Forzar a todos los valores por defecto que se aplicar a nivel de los empleados
ANTES DE 'Evaluate_Properties () se llama.
cuyos
valores de propiedades
RetVal = noaction
End If End
Sub
Microsoft Dynamics SL llamadas a la API de funciones 51
Nota: En las siguientes secciones, un cdigo de ejemplo puede exceder de una lnea. En esos casos, el smbolo indica un carcter de
continuacin de lnea. Toda la lnea debe estar en una sola lnea en la ventana de cdigo de evento.
Declaracin AliasConstant Alias de ciertas constantes utilizadas especficamente por transaccin de importacin.
Funcin ApplGetParms Recupera un parmetro de lnea de comando que se pasa por otra aplicacin de
Microsoft Dynamics SL.
Declaracin ApplSetParmValue Aade un parmetro a la lista de todos los parmetros que sern enviadas a una
aplicacin de llamada.
Funciones DBNavFetch Recupera un registro compuesto a partir de la base de datos utilizando una instruccin SQL.
Funcin FParm funcin de formato para un campo de flotador se pasa a una funcin de SQL.
Funcin GetDelGridHandle Devuelve el identificador de recursos de la matriz de memoria utilizada para almacenar
temporalmente las lneas de detalle eliminados de la designada
SAFGrid controlar.
Funcin GetSqlType Determinar que se est utilizando tipo de servidor de base de datos.
Declaracin IntlStrToDate Convierte cadena de fecha de fecha corta de Windows en formato de fecha base de
datos SQL.
Funcin IParm funcin de formato para un campo entero pasado a una funcin de SQL.
Declaracin MDisplay Visualizar el contenido actual de la matriz de memoria designada en su control de hoja de
clculo correspondiente.
Funcin MFindControlName Devuelve una lista de los nombres de los controles presentes en la aplicacin actual.
Funcin MGetLineStatus Devuelve el estado de la lnea del registro actual en la matriz de memoria designada.
Funcin MGetRowNum Devuelve el nmero de fila / registro del registro actual en la matriz de memoria
designada.
Declaracin tecla m Define un campo clave para una matriz de memoria previamente abierto.
Microsoft Dynamics SL llamadas a la API de funciones 53
Funcin MKeyFind Encuentra un registro especfico dentro de una matriz de memoria ordenados en base a los valores de
campo clave designadas.
Declaracin MKeyFld Define un campo clave para una matriz de memoria previamente abierto.
Declaracin MKeyOffset Define un campo clave para una matriz de memoria previamente abierto.
Declaracin mload Carga una matriz de memoria con todos los registros devueltos desde la base de datos
mediante una instruccin SQL.
Funcin MSetLineStatus Establece el estado de la lnea del registro actual en la matriz de memoria designada.
Declaracin MSetProp Establece las propiedades de una columna de cuadrcula en tiempo de ejecucin.
Declaracin MSetRowNum Establece el nmero de fila / registro actual de una matriz de memoria designada.
Declaracin msort Ordenar datos contenidos dentro de una matriz de memoria existente en base a campos
clave predefinidas.
Declaracin MUpdate Actualiza el registro actual matriz de memoria de una matriz de memoria designado con los
nuevos valores de los datos.
Funciones PVChkFetch Recupera un registro compuesto a partir de la base de datos utilizando una instruccin SQL
de la propiedad de un PV SAFMaskedText controlar.
Declaracin SetBufferValue Establece campo del almacenamiento intermedio de datos de una aplicacin Microsoft Dynamics SL
que subyace a un valor especificado.
Funcin Sparm funcin de formato para un campo de cadena que se pasa a una funcin de SQL.
Declaracin SqlCursor Asigna un cursor de SQL para una vista de una tabla.
Declaracin SqlErrException Permite que una aplicacin para atrapar a ciertos errores de SQL.
Funcin VBA_MExtend Extender la red de una aplicacin para que la estructura de otra mesa
puede ser aadido a la red.
Funciones VBA_MOpen Abrir una nueva matriz de memoria y devolver un nmero correspondiente matriz de
memoria nica.
Declaracin VBA_SetAddr Asigna una estructura de una tabla de base de datos especificado.
Microsoft Dynamics SL llamadas a la API de funciones 55
Declaracin AliasConstant
Utilice esta funcin para asignar un alias a ciertas constantes de Microsoft Dynamics SL utilizados especficamente por transaccin de importacin.
Esto puede ser til si est utilizando un idioma diferente (como palabras en ingls
Comentar, Insertar, y Cambio podra ser reemplazado por las palabras alternativas en otro idioma). Los valores posibles se enumeran a
continuacin.
Sintaxis
observaciones
Comentario
Insertar
Borrar
Cambio
Procesada
Separador
delimitador
LevelN (donde N es de 0 a 9)
Comprobado
Desenfrenado
prensa
Ejemplo
Llamar AliasConstant ( "Cambio", "Update") llame AliasConstant (
"Detalle")
56 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Funcin ApplGetParms
Recuperar un parmetro pasado por otra aplicacin SL kit de desarrollo de software de Microsoft Dynamics (Microsoft
SL SDK).
Sintaxis
ParmValue = ApplGetParms ()
observaciones
los ApplGetParms declaracin se puede utilizar para recuperar los parmetros, los cuales fueron aprobados originalmente por otra Microsoft
SDK SL aplicacin utilizando el Lanzamiento funcin. Realizar llamadas sucesivas a ApplGetParms puede recuperar varios parmetros.
Si la aplicacin que llama pasar parmetros a travs de secciones de parmetros con nombre, utilizando el
ApplSetParmValue declaracin en conjunto con el Lanzamiento funcin, entonces ApplGetParms
slo ser capaz de recuperar los parmetros de la seccin de Microsoft Dynamics SL defecto. los
ApplGetParmValue funcin es el nico medio por el cual la llamada aplicacin puede recuperar los parmetros de
cualquier seccin parmetro llamado aparte de la seccin Microsoft Dynamics SL defecto. los ApplGetParms funcin utiliza
el siguiente argumento:
Ejemplo
El ejemplo de cdigo proviene de las cuentas por pagar Mantenimiento Vendor ( 03.270.00) aplicacin lanzada:
Sub Form1_Load
'Variable para almacenar el parmetro pasado a esta pantalla' Bajo el escenario RDT, este cdigo estara en
'Pantalla se llama desde otra aplicacin. 'Establecer el valor del campo ID a lo que se'
End Sub
Ver tambin
Funcin ApplGetParmValue
Recuperar un parmetro pasado por otra aplicacin Microsoft SDK SL.
Sintaxis
observaciones
Los parmetros pasados a una aplicacin de Microsoft SL SDK pueden ser recuperados a travs de uno de dos mtodos diferentes: ApplGetParms
y ApplGetParmValue. Estas funciones se diferencian en que ApplGetParms
no soporta mltiples secciones de parmetros mientras ApplGetParmValue no proporcionar esta funcionalidad ms sofisticada. Por
consiguiente, ApplGetParmValue es el nico medio por el cual la llamada aplicacin puede recuperar los parmetros de cualquier
seccin parmetro llamado aparte de la seccin Microsoft Dynamics SL defecto. Por ejemplo, si la aplicacin que llama enva un
parmetro designado especficamente como un parmetro VBA, slo el ApplGetParmValue funcin se puede utilizar para recuperar
ese parmetro particular, ya que el nombre de seccin VBA se puede consultar de forma explcita a travs de la ParmSection argumento.
secciones de parmetros con nombre facilitar la eliminacin de los conflictos que pueden ocurrir en el programa de destino cuando la
aplicacin y el cdigo VBA aadido a travs del Administrador de personalizacin estn tratando de recibir diferentes parmetros.
Por ejemplo, las cuentas por pagar del mdulo
Mantenimiento de documentos ( 03.250.00) ventana puede recibir opcionalmente dos parmetros que facilitan la funcionalidad
drill-down: Nmero de Referencia y ID de proveedor. El evento Form_Load siempre llama ApplGetParms una vez para determinar si
los parmetros se han pasado a la aplicacin. Si existe incluso un parmetro que se supone que es el Nmero de Referencia y por lo
tanto las llamadas de solicitud ApplGetParms otra vez esperando que el siguiente parmetro que es el ID de proveedor. Si la adicin
de las llamadas a ApplGetParms utilizando cdigo VBA posteriormente personaliza esta pantalla, se producir un conflicto operativa.
Si una aplicacin tal haba de ser llamado con un solo parmetro, diseado para ser recibido por el cdigo VBA personalizado, este
lugar sera recibido por la llamada a ApplGetParms realizada por la aplicacin subyacente. En consecuencia, la llamada a
ApplSetParmValue y ApplGetParmValue superar este conflicto operativa, facilitando el uso de secciones de parmetros con nombre. El
uso de este mtodo ms sofisticado, los parmetros se pueden pasar directamente a la propia aplicacin y la costumbre cdigo VBA
usando los dos nombres de seccin estndar declaradas en el mdulo VBTools_VBA (es decir, PRMSECTION_VBRDT y
PRMSECTION_BSL). secciones de parmetros no son, sin embargo, limitada a estos dos nombres de seccin estndar. As, por ejemplo
[Seccin XYZ] es un nombre de seccin vlido. Se requieren los soportes desde secciones de parmetros se manejan a s mismos
similar a los nombres de seccin dentro de un archivo .INI. En el ejemplo que se ha mencionado anteriormente, un parmetro
personalizado se podra enviar a la pantalla de Cuentas por Pagar Mantenimiento de documentos en la seccin de parmetros de VBA tal
manera que slo las llamadas a
ApplGetParmValue especficamente solicitan parmetros VBA sera recuperar el parmetro. los ApplGetParmValue instruccin
ParmSection Cuerda Nombre de la seccin en el archivo de parmetros temporal de la que el parmetro debe ser
recuperada. Cualquier nombre de seccin se puede utilizar (como Seccin XYZ), siempre que la
aplicacin de llamada utiliza una seccin de parmetros de llamada as. El mdulo VBTools_VBA
contiene tres constantes simblicas que definen nombres de seccin estndar:
PRMSECTION_VBRDT, PRMSECTION_BSL y PRMSECTION_TI. PRMSECTION_TI est
reservado para el uso en conjuncin con transaccin de importacin. Por defecto, el parmetro se
recupera de la seccin representada por PRMSECTION_VBRDT si este argumento se deja en
blanco.
58 Personalizacin Reference Manager de Visual Basic para Aplicaciones
ParmName Cuerda nombre lgico del parmetro que se est recuperada. Por defecto, los nombres de parmetros se
numeran secuencialmente (PRM01, PRM02 .... PRM99) si no se mencionan explcitamente por la
llamada a ApplSetParmValue en la aplicacin de llamada.
Ejemplo
El siguiente ejemplo ilustra cmo pasar parmetros a una aplicacin de Microsoft SL SDK y cdigo VBA personalizada, al
mismo tiempo, evitar conflictos entre los dos. Cdigo en la aplicacin de llamada:
Cdigo de la aplicacin estndar de Microsoft SL SDK (es decir, no personalizado de cdigo) que recibe los parmetros estndar.
"Documento Nro")
cdigo Basic Script, superponiendo la aplicacin estndar de Microsoft SDK SL, diseado para recuperar los parmetros personalizados:
Ver tambin
Funcin ApplGetReturnParms
Recuperar un parmetro de regresar de una aplicacin secundaria ahora terminado.
Sintaxis
ParmValue = ApplGetReturnParms ()
observaciones
Si una aplicacin de Microsoft SL SDK necesita pasar parmetros de nuevo al programa de la que se llam originalmente se puede
hacer por medio de uno de los parmetros a ScreenExit. Cuando, posteriormente, el control vuelve a la aplicacin que llama, se
puede emitir una o ms llamadas a
ApplGetReturnParms para recuperar sucesivamente cada parmetro individual. los ApplGetReturnParms
ParmValue Cuerda El valor real del parmetro que se recupera de un programa secundario ahora
terminado.
Ver tambin
Declaracin ScreenExit
60 Personalizacin Reference Manager de Visual Basic para Aplicaciones
Declaracin ApplSetFocus
Establecer el foco a un control designado.
Sintaxis
Observaciones ApplSetFocus es el mtodo preferido para establecer explcitamente foco a un control de destino. Uso del mtodo
SetFocus de Visual Basic provocar un error fatal de Visual Basic si el control de destino est desactivado o invisible. Los
desarrolladores deben recordar siempre que el valor de la propiedad de tiempo de diseo del control de destino no se puede garantizar
para mantener siempre el mismo valor en tiempo de ejecucin. Por ejemplo, el control de destino puede ser tanto visible y habilitado en
la aplicacin estndar y por lo tanto el. Enfocar aparecer para que funcione correctamente durante la prueba. Sin embargo, el usuario
final puede, posteriormente, aplicar una personalizacin que desactiva el control de destino, el descubrimiento de un defecto sutil en la
aplicacin subyacente con respecto a su uso de la. Enfocar mtodo. los ApplSetFocus instruccin utiliza los siguientes argumentos:
Ejemplo
Llamada ApplSetFocus (" cDiscBal ")
Microsoft Dynamics SL llamadas a la API de funciones 61
Declaracin ApplSetParmValue
Aadir un parmetro adicional a la lista de todos los parmetros que se enviar a la siguiente aplicacin llamada por el Lanzamiento
funcin.
Sintaxis
observaciones
Microsoft utiliza el SDK SL Lanzamiento funcionar para iniciar otra aplicacin. Hay dos mtodos diferentes para el programa de
llamada para pasar parmetros al programa llamado. El primer mtodo consiste en pasar los parmetros para el programa llamado
con el argumento de Lanzamiento
diseado especficamente para este propsito. Los parmetros pasados a travs de este mtodo se agrupan juntos y se hacen pasar
directamente a la llamada aplicacin a travs de la lnea de comandos fsico en s. En consecuencia, en virtud de este mtodo, el
tamao y / o nmero de parmetros se limita a la longitud mxima de lnea de comandos menos el nmero de bytes utilizados por
Microsoft Dynamics SL para los requerimientos internos, que puede variar en funcin de la situacin. Un mtodo ms robusto de paso
de parmetros es el uso de la ApplSetParmValue declaracin en conjunto con el Lanzamiento funcin. La principal ventaja de utilizar
este mtodo es que permite la aplicacin de llamada a los parmetros de grupo en secciones con nombre y etiquetar explcitamente
parmetros individuales utilizando nombres de parmetros nicos. La agrupacin de los parmetros mencionados en secciones elimina
los conflictos que se producirn en el programa que se llama cuando la aplicacin en s, as como la costumbre cdigo VBA aadi a
travs del Administrador de personalizacin son a la vez intentar recibir diferentes parmetros. ver el ApplGetParmValue funcin para
una explicacin ms detallada de estos posibles conflictos. La primera llamada a ApplSetParmValue crear un archivo de parmetros
de destino temporal y colocar el primer parmetro en ese archivo. Por defecto, este archivo temporal se crea en el directorio Windows.
Este defecto puede cambiarse utilizando la entrada TempDirectory en la seccin [Varios] del archivo Solomon.ini. A continuacin se
presenta un ejemplo del directorio C: \ TEMP especificado como el directorio de archivo de parmetros en el Solomon.ini:
las posteriores llamadas a ApplSetParmValue escribir parmetros adicionales en el mismo archivo de parmetros de destino temporal. El
nombre de archivo totalmente calificado del archivo de parmetros completado a continuacin, se pasa al programa llamado por la Lanzamiento
funcin. Una vez que el programa llamado se ha cargado correctamente, se puede llamar a cualquiera ApplGetParms o ApplGetParmValue para
recuperar los diversos parmetros pasados desde el programa de llamada. Cuando el programa que se llama termina la ejecucin, se
eliminar automticamente el archivo de parmetros de destino temporal.
ApplSetParmValue Slo est diseado para facilitar el paso de parmetros a otras aplicaciones desarrolladas con
Microsoft SDK SL. los ApplSetParmValue instruccin utiliza los siguientes argumentos:
ParmSection Cuerda Nombre de la seccin en el archivo de parmetros temporales a los que hay que aadir el nuevo
parmetro. Cualquier nombre de seccin se puede utilizar como el mdulo VBTools_VBA contiene
tres constantes simblicas que definen nombres de seccin estndar Seccin XYZ.:
PRMSECTION_VBRDT, PRMSECTION_BSL y PRMSECTION_TI. PRMSECTION_TI est
reservado para el uso en conjuncin con transaccin de importacin. Por defecto, el nuevo
parmetro ser aadido a la seccin representada por PRMSECTION_VBRDT si este argumento se
deja en blanco.
62 Personalizacin Reference Manager de Visual Basic para Aplicaciones
ParmName Cuerda Nombre asignado al nuevo parmetro. Cualquier nombre puede ser asignado a un parmetro como
nmero de lote. Por defecto, el nuevo parmetro se le asignar el siguiente numeradas
secuencialmente nombre del parmetro (PRM01, PRM02 .... PRM99) si este argumento se deja en
blanco.
Ejemplo
El siguiente ejemplo ilustra dos mtodos diferentes de llamar ROI para mostrar el informe Lista de proveedores en la pantalla de todos los
vendedores que tienen un equilibrio mayor que cero. Pasar parmetros al retorno de la inversin a travs de un gran argumento de
parmetro para Lanzamiento. Este mtodo no funcionar con una amplia clusula WHERE ya que todo el contenido de ParmStr debe caber
en la lnea de comandos fsica.
WHERE" + PRMSEP ParmStr = ParmStr + "/ PSCRN" Lanzamiento de llamadas ( "ROI", ParmStr)
Pasar parmetros a utilizar ROI ApplSetParmValue en conjuncin con Lanzamiento. Usando este mtodo, el informe se ejecutar
correctamente independientemente de la duracin de la clusula WHERE.
Llamada ApplSetParmValue ( PRMSECTION_VBRDT, "", "03670 / RUN") Call ApplSetParmValue ( PRMSECTION_VBRDT, "", "03670S /
FORMATO") Call ApplSetParmValue ( PRMSECTION_VBRDT, "", "Vendor.CurrBal> 0 / WHERE") Call ApplSetParmValue ( PRMSECTION_VBRDT,
Ver tambin
Funcin CallChks
Realizar la comprobacin de errores en un objeto especfico de chk evento.
observaciones
Esta funcin es til cuando se desea ejecutar manualmente la comprobacin de errores en un objeto especfico porque el valor
de otro objeto ha sido cambiado. Esto le permite al disparador otra chk
evento bajo el control del programa. los CallChks funcin utiliza los
siguientes argumentos:
IntVar Entero Cualquier variable entera (serr, serr1 - serr12 declarado en el mdulo
VBTools_VBA estn reservados para este uso)
Ejemplo
'Objeto 1 evento Chk Dim Resultado #, # DrAmt, CrAmt # DrAmt =
entonces
"objeto1")
Ver tambin
Funcin DateCheck
Comprueba si una cadena de fecha en formato MMDDAAAA representa una fecha vlida.
Sintaxis
observaciones
RetVal Entero 0 si la cadena de fecha representa una fecha vlida. -1 indica un da vlido.
- 2 indica un mes vlido.
DateString Cuerda Fecha cadena para ser verificada. Debe estar en formato MMDDAAAA.
Ejemplo
datestr = "02291991" serr = DateCheck ( datestr)
Si serr = -1 Entonces
Entonces
El ejemplo realiza la comprobacin de errores en un campo de cadena que tiene formato de una fecha. El siguiente es su caso
Chk:
Sub cuser1_Chk (chkstrg $, retval%)
'Da invlido
Llamar Messbox ( "da no vlida, vuelva a entrar", MB_OK, "Mensaje") retval = errnomess ElseIf serr = -2 Entonces 'Mes
invlido
"Mensaje") retval =
Ver tambin
Declaracin StrToDate
Microsoft Dynamics SL llamadas a la API de funciones sesenta y cinco
Funcin DateCmp
Comparar dos valores de fecha.
Sintaxis
observaciones
Para determinar si es o no un valor de fecha es nulo uso DateCmp ( Fecha, NULLDATE). NULLDATE es variable global declarada en el
mdulo VBTools_VBA que se ha inicializado correctamente por el sistema en el inicio de todas las aplicaciones del SDK de Microsoft SL.
los DateCmp funcin utiliza los siguientes argumentos:
son iguales.
Ejemplo
Dim Dim TestDate1 Como SDATE
Llamar MessBox ( "Las fechas son iguales", MB_OK, "Mensaje") ElseIf serr1> 0 Then
Llame MessBox ( "invdate mayor", MB_OK, "Message") ElseIf serr1 <0, entonces
Funcin DateMinusDate
Devuelve el nmero de das entre dos fechas.
Sintaxis
observaciones
NbrDays Largo Number of days between Date1 and Date2 including the ending date. If
Date1 > Date2 then the number of days between the two dates will be a
negative value.
Example
Dim Date1 As Sdate Dim Date2 As
Sdate
See Also
DatePlusDays Statement, DatePlusMonthSetDay Statement
Microsoft Dynamics SL API Function Calls 67
DatePlusDays Statement
Add a designated number of days to an existing date.
Syntax
Call DatePlusDays( CurrDate, NbrDaysToAdd, ResultingDate)
Remarks
The DatePlusDays statement uses the following arguments:
NbrDaysToAdd Integer Number of days to add to CurrDate. Negative values are supported.
Example
Dim OldDate As Sdate Dim NewDate As
DaysToAdd, NewDate)
See Also
DateMinusDate Function, DatePlusMonthSetDay Statement
68 Customization Manager Reference Visual Basic for Applications
DatePlusMonthSetDay Statement
Add a designated number of months to an existing date and set the day portion of the resulting date to a specific day of
the month.
Syntax
Call DatePlusMonthSetDay( CurrDate, NbrMthsToAdd, SetSpecificDay, ResultingDate)
Remarks
The DatePlusMonthSetDay statement uses the following arguments:
NbrMthsToAdd Integer Number of months to add to CurrDate. Negative values are supported.
SetSpecificDay Integer Desired value for the day portion of the resulting date. In cases where
SetSpecificDay is beyond the last valid day for the relevant month, the
system will automatically set the actual day value equal to the last valid day
of that month.
ResultingDate SDate user-defined datatype Resulting date.
(declared in the
VBTools_VBA module)
Example
Dim OldDate As Sdate Dim NewDate As
MonthsToAdd% DayOfMonth = 30
MonthsToAdd = 3
Call StrToDate("11211992", OldDate) Call DatePlusMonthSetDay ( OldDate, MonthsToAdd, DayOfMonth, NewDate) 'NewDate will be
02/28/1993 even though the DayOfMonth is 30 Call MessBox("New Date is " + DateToStrSep(NewDate), MB_OK, "Message")
See Also
DateMinusDate Function, DatePlusDays Statement
Microsoft Dynamics SL API Function Calls 69
DateToIntlStr Function
Convert a specified date into the Windows short date style.
Syntax
ShortDateStr = DateToIntlStr( DateToConvert)
Remarks DateToIntlStr will convert a date from an SQL database format into a format governed by the Windows short
date style.
See Also
DateToStr Function, DateToStrSep Function, IntlStrToDate Statement, StrToDate Statement
DateToStr Function
Convert a date value from an SQL date format into a string in MMDDYYYY format.
Syntax
DateString = DateToStr( DateToConvert)
Remarks
The DateToStr function uses the following arguments:
Example
'Example sets a field to current system date Dim NewDate as Sdate Dim NewStrDate$
See Also
DateToStr Function, DateToStrSep Function, IntlStrToDate Statement, StrToDate Statement
70 Customization Manager Reference Visual Basic for Applications
DateToStrSep Function
Convert a date value from an SQL date format into a string in MM/DD/YYYY format.
Syntax
DateString = DateToStrSep( DateToConvert)
Remarks
The DateToStrSep and DateToStr functions differ only in the fact that DateToStrSep inserts a single character separator
between the month, day and year portions of the string. The DateToStrSep function uses the following arguments:
Example
Dim TodaysDate As Sdate Call GetSysDate(TodaysDate) Call MessBox("Current Date is " + DateToStrSep( TodaysDate),
MB_OK, "Message")
See Also
DateToStr Function, DateToStrSep Function, IntlStrToDate Statement, StrToDate Statement
Microsoft Dynamics SL API Function Calls 71
DBNavFetch Functions
Retrieve a composite record from the database using an SQL statement from the DBNav property of an
SAFMaskedText control.
Syntax
RetVal = DBNavFetch1( Ctrl, Cursor, SQLParmValue, bTable1, bTable1Length) RetVal = DBNavFetch4( Ctrl, Cursor,
SQLParmValue, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length)
RetVal = DBNavFetch8( Ctrl, Cursor, SQLParmValue, bTable1, bTable1Length, bTable2, bTable2Length, bTable3,
bTable3Length, bTable4, bTable4Length, bTable5, bTable5Length, bTable6, bTable6Length, bTable7, bTable7Length,
bTable8, bTable8Length)
Remarks
DBNavFetch1, DBNavFetch4 and DBNavFetch8 can be used to fetch a composite record based on the SQL text from the
DBNav property of the SAFMaskedText control specified in the Ctrl
parameter. These functions are not applicable if the DBNav property does not contain either an SQL statement or stored
procedure name. All SAFMaskedText controls have both a PV and a DBNav property each of which can contain an SQL
statement. The DBNavFetch1 and PVChkFetch1 functions are similar except that they use SQL statements from two
different properties, namely the DBNav and PV properties. Normally the PVChkFetch1 function will be used in conjunction
with the PV property to facilitate both a Possible Values window as well as the actual fetch of a record. If the program
requirements specify the need to fetch a record but not supply a Possible Values window then DBNavFetch1
will need to be used in conjunction with the DBNav property. This situation can arise on screens containing multiple key
fields where the last key field does not need a Possible Value window. An example of such a case is Employee W2 History
(02.260) which has two key fields: Employee ID and Calendar Year. The requirements for the screen are that the user be
forced to enter a valid Employee ID based on the Employee table which should be viewable via a Possible Values window.
However no table exists in the system to define a valid Calendar Year and therefore a Possible Values window is not
applicable since any numeric value is valid. Once the last key field has been entered a unique record corresponding to
both key fields needs to be fetched from the database. Since Calendar Year is the last key field, and a Possible Value
window is not required for that field, the DBNavFetch1 function was used in conjunction with the DBNav property of the
Calendar Year control.
DBNavFetch1 is designed for SQL statements returning data from a single table. For more advanced SQL statements
having one or more table joins either DBNavFetch4 or DBNavFetch8
can be used.
DBNavFetch1, DBNavFetch4 and DBNavFetch8 are all designed to fetch a single composite record. For example if an
SQL statement contains eight table joins, DBNavFetch8 does not return eight records from a single table. On the contrary
it returns a single record from each of the eight tables. Consequently these functions are not used in conjunction with the
DBNav property of the SAFGrid control. The DetailLoad statement uses the DBNav property of the
SAFGrid control to load the grid with multiple records from one or more tables.
72 Customization Manager Reference Visual Basic for Applications
The DBNavFetch1 function uses the following arguments ( DBNavFetch4 and DBNavFetch8
respectively have four and eight table structures and corresponding lengths. PNULL should be passed for unused table
structure parameters as well as a corresponding length of zero such as PNULL, 0)
Ctrl Control containing the DBNav property to be used as the SQL statement. Can
optionally be PNULL if the call is made within the Chk event of the control
whose DBNav property is being used.
SQLParmValue String Key value passed as the last parameter to the restriction clause of the
DBNav SQL statement.
bTable1 User-defined Table structure corresponding to the primary table in the DBNav SQL
datatype statement.
bTable1Length Integer Size of first table structure. For example, LenB(bTable1).
Note: It is critical to use LenB() instead of Len() for all non- null table length
parameters.
Example
Sub cCalYr_Chk (chkstrg As String, retval As Integer)
See Also
PVChkFetch Functions
Microsoft Dynamics SL API Function Calls 73
DispFields Statement
Display the value of the underlying data field(s) corresponding to the designated control(s).
Syntax
Call DispFields( Form, Control)
Remarks
Each Microsoft Dynamics SL data control is associated with an underlying Visual Basic variable via a combination of its FieldName
property and an associated VBA_SetAddr call. The system will automatically redisplay the new value of relevant controls
any time the system is the entity modifying the value of the underlying Visual Basic variable, such as when a new record is
loaded. However, when the application directly modifies the value of a Visual Basic variable underlying a Microsoft
Dynamics SL data control, then it may also need to call the DispFields
Example
The following code snippet from the Payroll modules Earnings Type Maintenance ( 02.270.00) screen illustrates how the DispFields
statement should be used after the Visual Basic variable underlying a particular data control has been modified
programmatically. The code is from the
Chk event of the Earnings Type combo box control.
'Displaying all fields on a form If Level = 0 Then
'Set defaults for all objects on NewInfo subform 'then re-display the results serr1 =
DateToStr(NewDate)
See Also
FieldName Property, MDisplay Statement, TabIndex Property, VBA_SetAddr Statement
74 Customization Manager Reference Visual Basic for Applications
DispForm Statement
Display a designated subform.
Syntax
Call DispForm( SubFormName, CenterIt)
Remarks DispForm will cause the designated subform to be displayed modally, meaning that no other form from the
same application can receive focus until the subform is hidden via a call to
HideForm.
Form1 is always displayed automatically by the system. Consequently, this call is only necessary for subforms.
The DispForm statement uses the following arguments:
CenterIt Integer TRUE is the subform is to be centered on the screen. FALSE if the form should
be displayed at its design time coordinates.
Example
'Display new subform Call DispForm(" NewForm", True)
See Also
HideForm Statement
Microsoft Dynamics SL API Function Calls 75
DParm Function
Convert a date into an SQL parameter string.
Syntax
SQLParmStr = DParm( DateToConvert)
Remarks
The DParm function uses the following arguments:
Example
'Example retrieves the last voucher date for 'current vendor and selects a count of all documents 'less
Dim SqlStr$
Sdate
DateComp.Val = GetObjectValue("clastvodate")
+ Dparm( DateComp)
See Also
FParm Function, IParm Function, SParm Function
76 Customization Manager Reference Visual Basic for Applications
Edit_Cancel Statement
Executes the Cancel toolbar button.
Syntax
Call Edit_Cancel
Remarks
This function corresponds to the Cancel selection on the Edit menu and toolbar. Use of this function allows you to
execute the Cancel function from a VBA program.
Example
This example uses a button to perform the Cancel function.
Sub Cancel_Click()
Call Edit_Cancel
End Sub
See Also
Edit_Close Statement, Edit_Finish Function
Edit_Close Statement
Executes the Close toolbar button.
Syntax
Call Edit_Close
Remarks
This function corresponds to the Close selection on the Edit menu and toolbar. Use of this function allows you to
execute the Close function from a VBA program.
Example
This example uses a button to perform the Close function.
Sub Close_Click()
Call Edit_Close
End Sub
See Also
Edit_Next Function, Edit_Last Function
Microsoft Dynamics SL API Function Calls 77
Edit_Delete Function
Executes the Delete toolbar button.
Syntax
RetVal = Edit_Delete ( LevelNumber)
Remarks
This function corresponds to the Delete selection on the Edit menu and toolbar. Use of this function allows you to
execute the Delete function on the specified Level% from a VBA program. The Edit_Delete function uses the
following arguments:
Example
This example navigates to the fourth row in a journal entry screen, and then deletes the row.
Dim LvlStr$, Lvl%, I%
See Also
Edit_New Function, Edit_Save Statement
78 Customization Manager Reference Visual Basic for Applications
Edit_Finish Function
Executes the Finish toolbar button.
Syntax
RetVal= Edit_Finish( LevelNumber)
Remarks
This function corresponds to the Finish selection on the Edit menu and toolbar. Use of this function allows you to
execute the Finish function from a VBA program. The Edit_Finish function uses the following arguments:
Example
This example performs Finish using a button.
serr1= Edit_Finish
See Also
Edit_Cancel Statement, Edit_Save Statement
Microsoft Dynamics SL API Function Calls 79
Edit_First Function
Executes the First toolbar button.
Syntax
RetVal = Edit_First ( LevelNumber)
Remarks
This function corresponds to the First selection on the Edit menu and toolbar. Use of this function allows you to execute
the First database navigation function on the specified Level% from a VBA program. The Edit_First function uses the
following arguments:
Example
This example navigates through detail lines of an existing journal entry. It goes to the first line first, and then goes to the
next line until done.
Sub NavToEndOfList_Click()
See Also
Edit_Next Function, Edit_Last Function
80 Customization Manager Reference Visual Basic for Applications
Edit_Last Function
Executes the Last toolbar button.
Syntax
RetVal = Edit_Last ( LevelNumber)
Remarks
This function corresponds to the Last selection on the Edit menu and toolbar. Use of this function allows you to execute
the Last database navigation function on the specified Level% from a VBA program. The Edit_Last function uses the
following arguments:
Example
This example navigates through detail lines of an existing journal entry. It goes to the last line first and then to the
previous line until finished.
Sub NavToTopOfList_Click()
While serr = 0
See Also
Edit_Next Function, Edit_First Function
Microsoft Dynamics SL API Function Calls 81
Edit_New Function
Executes the New toolbar button.
Syntax
RetVal = Edit_New ( LevelNumber)
Remarks
This function corresponds to the New selection on the Edit menu and toolbar. Use of this function allows you to execute
the New function on the specified Level% from a VBA program. The Edit_New function uses the following arguments:
Example
This example inserts a new document under program control.
Dim LvlStr$, Lvl%
See Also
Edit_Save Statement, Edit_Delete Function
82 Customization Manager Reference Visual Basic for Applications
Edit_Next Function
Executes the Next toolbar button.
Syntax
RetVal = Edit_Next ( LevelNumber)
Remarks
This function corresponds to the Next selection on the Edit menu and toolbar. Use of this function allows you to execute
the Next database navigation function on the specified Level% from a VBA program. The Edit_Next function uses the
following arguments:
Example
This example navigates through detail lines of an existing journal entry. It goes to the first line first and then goes to the
next line until done.
Sub NavToEndOfList_Click()
This example inserts a new row into row six of an existing General Ledger journal entry.
Sub InsertAtRowSix_Click()
Lvl)
Cntr = 1
serr = Edit_First(Lvl)
serr = SetObjectValue("cacct","3080")
Microsoft Dynamics SL API Function Calls 83
SetObjectValue("ctrandate","09071994")
See Also
Edit_Prev Function, Edit_Last Function
84 Customization Manager Reference Visual Basic for Applications
Edit_Prev Function
Executes the Prev toolbar button.
Syntax
RetVal = Edit_Prev ( LevelNumber)
Remarks
This function corresponds to the Previous selection on the Edit menu and toolbar. Use of this function allows you to
execute the Previous database navigation function on the specified Level% from a VBA program. The Edit_Prev function
uses the following arguments:
Example
This example navigates through detail lines of an existing journal entry. It goes to the last line first and then to the
previous line until finished.
Sub NavToTopOfList_Click()
While serr1 = 0
See Also
Edit_Next Function, Edit_First Function
Microsoft Dynamics SL API Function Calls 85
Edit_Save Statement
Executes the Save toolbar button.
Syntax
Call Edit_Save
Remarks
This function corresponds to the Save selection on the Edit menu and toolbar. Use of this function allows you to
execute the Save database function from a VBA program.
Example
Dim TimeOfDay As Stime Call
GetSysTime(TimeOfDay)
See Also
Edit_New Function, Edit_Delete Function
86 Customization Manager Reference Visual Basic for Applications
FPAdd Function
Add two double-precision floating-point values together with a designated rounding precision.
Syntax
Result = FPAdd( Dbl1, Dbl2, Precision)
Remarks
Error conditions occurring during the addition operation, such as an overflow error, will be handled automatically by the
system. These types of errors will cause the appropriate error message to be either displayed on the screen or written to
the process status log depending on the context in which the error occurred. After an error condition has been properly
reported, the application will be terminated. The FPAdd function uses the following arguments:
Note: The precision parameter can be an explicit precision value as well as one of the following symbolic
constants defined in the VBTools_VBA module:
Example
'Add the current to future balance for a total balance Dim CurrentBalance# Dim FutureBalance# Dim
TotalBal#
See Also
FPDiv Function, FPMult Function, FPRnd Function, FPSub Function
Microsoft Dynamics SL API Function Calls 87
FParm Function
Convert a double-precision floating-point value into an SQL parameter string.
Syntax
SQLParmStr = FParm( DblToConvert)
Remarks
The FParm function uses the following arguments:
Example
Dim MaxAmount# Dim
SqlStr$
SqlStr = "Select Count(*) From ARDoc Where DocBal > " SqlStr = SqlStr + FParm( MaxAmount) Call
Sql(c1, SqlStr)
See Also
DParm Function, IParm Function, SParm Function
88 Customization Manager Reference Visual Basic for Applications
FPDiv Function
Divide one double-precision floating-point value by another with a designated rounding precision.
Syntax
Result = FPDiv( Dbl1, Dbl2, Precision)
Remarks
This function will divide the value of Dbl1 by Dbl2 and return the result. Error conditions occurring during the division
operation, such as division by zero, will be handled automatically by the system. These types of errors will cause the
appropriate error message to be either displayed on the screen or written to the process status log depending on the
context in which the error occurred. After an error condition has been properly reported, the application will be terminated.
The FPDiv function uses the following arguments:
Note: The precision parameter can be an explicit precision value as well as one of the following symbolic
constants defined in the VBTools_VBA module:
Example
Dim Var1#, Var2#, Result# Var1 = 100 Var2 = 10 Result = FPDiv( Var1,
See Also
FPAdd Function, FPMult Function, FPRnd Function, FPSub Function
Microsoft Dynamics SL API Function Calls 89
FPMult Function
Multiply two double-precision floating-point values together to a designated rounding precision.
Syntax
Result = FPMult( Dbl1, Dbl2, Precision)
Remarks
Error conditions occurring during the multiplication operation, such as an overflow error, will be handled automatically by
the system. These types of errors will cause the appropriate error message to be either displayed on the screen or written
to the process status log depending on the context in which the error occurred. After an error condition has been properly
reported, the application will be terminated. The FPMult function uses the following arguments:
Note: The precision parameter can be an explicit precision value as well as one of the following symbolic
constants defined in the VBTools_VBA module:
Example
Dim Var1#, Var2#, Result# Var1 = 100 Var2 = 10 Result = FPMult( Var1,
See Also
FPAdd Function, FPDiv Function, FPRnd Function, FPSub Function
90 Customization Manager Reference Visual Basic for Applications
FPRnd Function
Round a double-precision floating-point value to a designated rounding precision.
Syntax
Result = FPRnd( DblToRound, Precision)
Remarks
Error conditions occurring during the rounding operation, such as an overflow error, are handled automatically by the
system. These types of errors will cause the appropriate error message to be either displayed on the screen or written to
the process status log depending on the context in which the error occurred. After an error condition has been properly
reported, the application will be terminated. The FPRnd function uses the following arguments:
Note: The precision parameter can be an explicit precision value as well as one of the following symbolic
constants defined in the VBTools_VBA module:
Example
The example issues an SQL statement to retrieve a sum of total documents. It displays the results in a message box
and formats the number.
Dim SqlStr$ Dim
Result#
See Also
FPAdd Function, FPDiv Function, FPMult Function, FPSub Function
Microsoft Dynamics SL API Function Calls 91
FPSub Function
Subtract one double-precision floating-point value from another with a designated rounding precision.
Syntax
Result = FPSub( Dbl1, Dbl2, Precision)
Remarks
This function will subtract the value of Dbl2 from Dbl1 and return the result. Error conditions occurring during the
subtraction operation, such as an overflow error, will be handled automatically by the system. These types of errors will
cause the appropriate error message to be either displayed on the screen or written to the process status log depending
on the context in which the error occurred. After an error condition has been properly reported, the application will be
terminated. The FPSub function uses the following arguments:
Note: The precision parameter can be an explicit precision value as well as one of the following symbolic
constants defined in the VBTools_VBA module:
Example
Dim Var1#, Var2#, Result# Var1 = 1000 Var2 = 300 Result = FPSub(
See Also
FPAdd Function, FPDiv Function, FPMult Function, FPRnd Function
92 Customization Manager Reference Visual Basic for Applications
GetBufferValue Statement
Obtains an underlying Microsoft Dynamics SL applications data buffer field value.
Syntax
Call GetBufferValue( bTable.FieldName, Str)
Remarks
If a VBA application issues its own VBA_SetAddr calls it can then reference any of these structures from within code.
However, if the underlying applications structures need to be referenced and these fields are not represented as objects
on the form, this statement allows the VBA application to obtain these values. If the fields were objects on the form, the
VBA application can simply issue GetObjectValue instead. The GetBufferValue statement uses the following arguments:
Str String String variable in which to store the contents of the buffers field value
Example
' get account number from gltran record Dim AccountValue As String * 10 Call GetBufferValue("
bgltran.acct",AccountValue)
See Also
SetBufferValue Statement
Microsoft Dynamics SL API Function Calls 93
GetDelGridHandle Function
Returns the resource handle of the memory array used to temporarily hold detail lines deleted from the designated SAFGrid
control.
Syntax
DelMemHandle = GetDelGridHandle( SpreadSheetObj)
Remarks
Each SAFGrid control is associated with two underlying memory arrays that the system opens automatically during Form
Load. The primary memory array holds the records that are actually visible in the grid. The resource handle to this primary
memory array is actually returned by the GetGridHandle function. However another array is also created to temporarily
hold user- deleted records until a save operation is performed and the deletions are actually committed to the database.
The resource handle to this memory array can be retrieved using the
GetDelGridHandle function.
Once the resource handle for the deleted record memory array has been retrieved, the application can use it to
loop through user-deleted records using calls such as MFirst and
MNext.
The GetDelGridHandle function uses the following arguments:
Example
serr1 = GetDelGridHandle("Spread1")
See Also
GetGridHandle Function
94 Customization Manager Reference Visual Basic for Applications
GetGridHandle Function
Obtains the grid handle for a Spreadsheet object.
Syntax
IntVar = GetGridHandle ( SpreadControlName$)
Remarks
Returns the memory array handle for the specified spreadsheet object. Useful if the application wants to use memory
array functions to navigate through a spreadsheet object. Should be used with extreme caution since the underlying
application may override memory array assumptions performed in the VBA program. The GetGridHandle function
uses the following arguments:
Example
Dim MemHandle As Integer MemHandle = GetGridHandle(" Spread1")
See Also
MSet Statement
Microsoft Dynamics SL API Function Calls 95
GetObjectValue Function
Obtains the value of a specified object on the form.
Syntax
RetVal = GetObjectValue( ControlName )
Remarks
Whenever a VBA application needs to obtain data values from any of the controls on the form, this function is used. The GetObjectValue
function uses the following arguments:
ControlName String Name of the control whose field value you want to obtain.
Example
Dim TestDate1 As Sdate TestDate1.Val = GetObjectValue(" cinvcdate") 'Double field
example Dim CrTotal# CrTotal = Val( GetObjectValue (" ccrtot")) 'Logical field
example
'Note that an integer variable type is declared Dim Var1% Var1 = GetObjectValue(" cmultichk")
If Var1 = 0 Then
ccountry")
See Also
SetObjectValue Function
96 Customization Manager Reference Visual Basic for Applications
GetProp Function
Obtains a property value for a specified object.
Syntax
RetVal = GetProp( ObjectName, PropName, PropValue)
Remarks
This function allows the VBA application to obtain a property value of any object on the screen. In addition to the property
value, the application can also obtain the level associated with the particular object. This function is useful in the Edit_ functions
as well as the SetProp
functions because you can check the value of the property before setting it. The GetProp function
uses the following arguments:
PropName String Property name you want the value of. Note: Any native property name that is available for
the object may be specified.
The following values for the PropertyName argument are defined as symbolic constants in the VBTools_VBA module:
PROP_CAPTION String
PROP_CUSTLIST String
PROP_HEADING String
PROP_LEVEL String
PROP_MASK String
PROP_MIN String
PROP_MAX String
Example
This example navigates through batches in the General Ledger Journal Transactions ( 01.010.00) screen.
Sub NavThruBatches_Click()
' Since cbatnbrh is a key field, level will be ' returned as "0,k" not "0"
' So declare lvlstr as a one-character string, so ' we get back only "0", and then manually convert it ' for
Lvl = Val(LvlStr)
NotFound
DoEvents
See Also
SetProp Statement, Edit_Next Function
98 Customization Manager Reference Visual Basic for Applications
GetSqlType Function
Determine which type of database server is being utilized.
Syntax
SqlType = GetSqlType()
Remarks
Microsoft Dynamics SL currently only supports the use of Microsoft SQL Server databases. This is an old API that
used to support multiple database types. For backward compatibility it has been preserved. The GetSqlType function
returns one of the following integer global constants declared in the VBTools_VBA module:
Example
Dim SqlDatabaseBeingUtilized As Integer
SqlDatabaseBeingUtilized = GetSqlType()
Microsoft Dynamics SL API Function Calls 99
GetSysDate Statement
Retrieve the current system date.
Syntax
Call GetSysDate( Date)
Remarks
The GetSysDate statement uses the following arguments:
Example
This sample routine sets an existing date field to the system date.
Sub setdate_Click()
See Also
GetSysTime Statement
100 Customization Manager Reference Visual Basic for Applications
GetSysTime Statement
Retrieve the current system time.
Syntax
Call GetSysTime( Time)
Remarks
The GetSysTime statement uses the following arguments:
Example
'Obtain current system time Dim SystemTime As
See Also
GetSysDate Statement
HideForm Statement
Hide a designated subform previously displayed via a call to DispForm.
Syntax
Call HideForm( SubFormName)
Remarks
This function is typically used in the click event of the OK or Cancel button of the designated subform. The HideForm statement
uses the following arguments:
Example
Sub OkButton_Click()
See Also
DispForm Statement
IncrStrg Statement
Increment a string representation of a whole number value.
Microsoft Dynamics SL API Function Calls 101
Syntax
Call IncrStrg( StringNbr, Length, Increment)
Remarks
The IncrStrg statement uses the following arguments:
Length Integer Size of StringNbr. It is not required that this value equal the full size of StringNbr. For
example if the string can actually hold 10 bytes but currently the developer only desires to
use 6 byte values then a value of 6 can be passed.
Example
Dim BatNbrLength As Integer
BatNbrLength = LenB(Trim$(bGLSetup.LastBatNbr))
'Increment last batch number to the next sequential value (within the 'size of batch numbers actually being used - i.e., BatNbrLength).
IntlStrToDate Statement
Convert a date string from the Windows short date style into an SQL database date format.
Syntax
Call IntlStrToDate( DateStrToConvert, SQLDate)
Remarks IntlStrToDate can be used to convert a string formatted according to the Windows short date style into a
format suitable for storage in a date field within the SQL database. The IntlStrToDate statement uses the following
arguments:
See Also
DateToIntlStr Function, DateToStr Function, DateToStrSep Function, StrToDate Statement
102 Customization Manager Reference Visual Basic for Applications
IParm Function
Convert an integer into an SQL parameter string.
Syntax
SQLParmStr = IParm( IntToConvert)
Remarks
The IParm function uses the following arguments:
IntToConvert Integer Integer value to convert. Note: INTMIN and INTMAX are global constants available that
may optionally be used. These represent 32768 and 32767 respectively, which are the
minimum and maximum small integer range values.
Example
These examples assume the following SQL statement was used to create a stored procedure called
GLTran_Module_BatNbr_LineNbr:
Select * from GLTran
@parm2
LineNbr;
This code snippet illustrates how the previously-defined stored procedure can be used to fetch a single transaction having
a LineNbr of 84 in General Ledger batch 000123.
SqlStr = " GLTran_Module_BatNbr_LineNbr" + SParm("GL") +
This code snippet illustrates how the previously-defined stored procedure can be used to fetch all transactions in General
Ledger batch 000123.
SqlStr = " GLTran_Module_BatNbr_LineNbr" + SParm("GL") +
See Also
DParm Function, FParm Function, SParm Function
Microsoft Dynamics SL API Function Calls 103
Is_TI Function
Returns whether or not the Microsoft Dynamics SL application is in Transaction Import mode.
Remarks
This function is useful when you want to suppress user-responses and/or dialogs when the application is running in
Transaction Import mode. The Is_TI function returns the following:
Example
The following example determines whether the application is in Transaction Import mode:
If Is_TI = False Then
'Perform logic or routine only desired in standard mode. ( not Transaction Import mode) End If
See Also
AliasConstant Statement
104 Customization Manager Reference Visual Basic for Applications
Launch Function
Launches another executable program.
Syntax
RetVal = Launch ( CommandLine, SAFApp, WaitFlag, WindowFlag)
Remarks
Allows you to launch any Microsoft Dynamics SL window (or any other Windows application) from any other Microsoft
Dynamics SL window. You can also pass parameters to the windows and use the ApplGetParms function in the
Launched application to retrieve the parameters. The Launch function uses the following arguments:
CommandLine String The command line required to execute the application (parameters included separated
by PRMSEP constant declared in the VBTools_VBA module).
SAFApp Integer Whether or not the application is a Microsoft Dynamics SL application (True or False).
WaitFlag Integer Whether or not the launched application is modal. When the launched application is modal,
no other form is able to be clicked until the application is closed. When this parm is True
and the application being launched is another application, then the launched application
shares the same SQL session with the application that launched it. Therefore, an extra
session is not used. This exhibits the same behavior as Quick Maintenance.
WindowFlag Integer State of the launched application. The VBTools_VBA module has two constants
declared for this purpose: LaunchMaximize or LaunchMinimize. Zero launches the
application in its normal state.
To launch a Microsoft Dynamics SL report, you must launch the ROI application with the appropriate parameters. The
following are the available parameters (and their descriptions) which you can pass to ROI:
Parameter Description
/DEBUG Creates a text file called RSWRUN.? in the Microsoft Dynamics SL Program directory. This TXT
file contains all of the parameters passed to the report. (Only useful for debugging purposes)
/TEMPLATE Follows the Report Template name that you wish to load for the report.
Example
The following is code for the Accounts Payable Vendor Maintenance ( 03.270.00) launched application:
Sub Form1_Load
' Variable to store the passed Parameter to this screen Dim VendorParm$
Microsoft Dynamics SL API Function Calls 105
Then
' Screen was called from another application. ' Set the value of the ID field to what was '
The following code is for the Accounts Payable modules Voucher and Adjustment Entry
(03.010.00) screen (the launching application). Even though this example uses a button, it could be placed in the Chk event
of a particular control. The syntax would be similar, except that chkstrg is evaluated and passed to the Launch( ) function:
Sub VendorScrn_Click()
' Obtain the Current ID in this screen and pass ' as a parameter to other EXE Dim CmdLine$
' Note that VendParm is passed twice with a PRMSEP between ' Also note the space following 0327000. This is
CmdLine = "0327000 " + VendParm + PRMSEP + VendParm ' The third parm indicates Wait = True.
This will allow ' the Launched application to share the same SQL session, ' therefore, an extra session is not used.
This exhibits the ' same behavior from a shared session perspective as Quick ' Maintenance.
Launching ROI
The following example will print the Accounts Payable Vendor Trial Balance ( 03.650.00) for the current vendor in the Vendor
Maintenance ( 03.270.00) window. This code is placed in the Click event of a button. Note that you must have one space
following ROI.exe in the first parameter.
Dim VendorId$, ParmStr$
VendorId = GetObjectValue("cvendid")
See Also
ApplGetParms Function, ApplGetParmValue Function, ApplSetParmValue Statement
106 Customization Manager Reference Visual Basic for Applications
MCallChks Function
Perform error checking on a specific grid objects column.
Remarks
This function is useful when you want to manually execute error checking on a grid object column because another
objects value has been changed. This allows you to trigger the Chk
event under program control. The MCallChks function uses the
following arguments:
See Also
CallChks Function, GetGridHandle Function
MClear Statement
Delete all records from the designated memory array.
Syntax
Call MClear( MemHandle)
Remarks
The MClear statement can be used to clear an existing memory array of its contents. The array will stay allocated and can
be subsequently re-used. The MClear statement uses the following arguments:
See Also
VBA_MOpen Functions
Microsoft Dynamics SL API Function Calls 107
MClose Statement
Close an existing memory array.
Syntax
Call MClose( MemHandle)
Remarks MClose can be used to close a memory array previously opened using one of the VBA_MOpen
Example
This example illustrates how to close a memory array that is no longer needed by the application.
'Allocate cursor
Call SqlCursor( CSR_Account, NOLEVEL) 'Initialize cursor with a SQL statement and immediately fetch
first record
SqlStr = "Select * from Account order by Acct" Account_Fetch = SqlFetch1(CSR_Account, SqlStr, bAccount, Len(bAccount)) 'Read through all subsequent
While( Account_Fetch = 0)
record
See Also
VBA_MOpen Functions
108 Customization Manager Reference Visual Basic for Applications
MDelete Function
Delete the current record from the designated memory array.
Syntax
RecFetch = MDelete( MemHandle, RecMaintFlg)
Remarks
The current record in a memory array can be deleted by using the MDelete function. After the record is deleted, the
system will automatically navigate to the next memory array record since there must always be a current record in
memory arrays, assuming of course that one or more records exist. Consequently, the return value and corresponding
record status apply to the next record after the deleted record.
When this call is used on a memory array associated with an SAFGrid control, an MDisplay call will be necessitated to
properly synchronize the SAFGrid appearance with the memory array. The MDelete function uses the following
arguments:
RecMaintFlg Integer Status of the memory array record (assuming it was successfully fetched). the
VBTools_VBA module contains the following symbolic constants defining possible
memory array record status values: INSERTED, UPDATED and NOTCHANGED
See Also
MDisplay Statement, MInsert Statement, MUpdate Statement
Microsoft Dynamics SL API Function Calls 109
MDisplay Statement
Display the current contents of the designated memory array in its corresponding SAFGrid
control.
Syntax
Call MDisplay( MemHandle)
Remarks
Each SAFGrid control is associated with an underlying memory array that is opened automatically. Any time data within
this memory array is modified directly by the application, as opposed to by the user, the SAFGrid control must be
subsequently redisplayed. When MDisplay is called, the current memory array record will be displayed at the top of the
SAFGrid control. Thus, for example, if the application wants the first memory array record to display at the top of the SAFGrid
control it should initially call MFirst to move to the first record and then call MDisplay.
Example
Sub cBegProcessing_Click ()
'Explicitly initialize processing counter to zero BEFORE calling 'ProcValidBatch() for the FIRST time.
Nbr_Of_Batches_Processed = 0
Call ProcValidBatch(Nbr_Of_Batches_Processed)
Else
End If
110 Customization Manager Reference Visual Basic for Applications
Wend
'Redisplay the grid with the modified contents of the memory array.
End Sub
Microsoft Dynamics SL API Function Calls 111
Mess Statement
Displays a message from the message file and waits for the user to choose a button.
Syntax
Call Mess( MsgNumber)
Remarks
During installation, an ASCII text file called Messages.csv is copied to the Microsoft Dynamics SL program directory. This
file contains all messages relating to the Microsoft Dynamics SL product, including all independently developed
applications created with Microsoft SL SDK. Each message has, among other things, a message number. A particular
message can be displayed to the screen by merely passing its associated message number to the Mess
statement. The Messf statement should be used if the actual text of the message contains replaceable parameters. The MessResponse
function can be used to determine which button was chosen by the user to close the message box.
The standard Visual Basic MsgBox statement should not be used in applications developed with Microsoft SL SDK in order
to avoid conflicts with other utilities such as Cut/Copy/Paste and Transaction Import. These utilities have built-in
sophistication to respond to messages from the underlying application during the particular operation being performed such
as paste or import. However, this automated functionality does not apply to messages displayed using the standard Visual
Basic MsgBox statement. The MessBox statement has been provided to facilitate similar functionality to the standard
Visual Basic MsgBox statement with the exception that MessBox
does not conflict with other Microsoft Dynamics SL utilities. The Mess statement
uses the following arguments:
Each record (message) contained within the Messages.csv file contains the following fields separated by a comma:
Message Number Message number which is required by most of the message APIs such as
Mess.
Category 0 for all messages. All independently developed applications must also use 0.
Record Type S for messages created and maintained by Microsoft. Independent developers should not
use S for their new messages since they could be deleted or modified by Microsoft.
Unattended Default Button This value is used by Transaction Import to respond to messages displayed
by the underlying application during the import operation.
Message Text Actual text of the message. Replaceable parameters appear as %s. For example: My first
name is %s and my last name is %s.
112 Customization Manager Reference Visual Basic for Applications
The Box Type field within the Messages.csv file can have the following values:
16 Stop OK OK
48 Exclamation OK OK
64 Information OK OK
33 Question OK / Cancel OK
Example
The Payroll modules Employee Maintenance ( 02.250.00) window allows the user to enter the number of personal
exemptions claimed by any particular employee on the Miscellaneous Information subscreen. Any time this value is
changed the user is prompted, via a message, as to whether or not the new total number of personal exemptions is to be
utilized by each individual deduction for calculation purposes.
Message number 739 is the actual message displayed and its associated text in the message file reads, Do you want to
update the employees deductions with the new exemption value? This particular message also displays two buttons in
the message box: a Yes button and a No
button. The MessResponse function is subsequently called to determine which of these two buttons the user actually
selected to close the message box.
Sub cDfltPersExmpt_Chk (chkstrg As String, retval As Integer)
MemArray_NbrRecs = MRowCnt(MemArray_EmpDeduction) 'If the memory array has any records in it then prompt the user
'whether or not he/she wants to update the number of PERSONAL 'EXEMPTIONS on ALL existing employee deductions.
End Sub
' Warning - Qty in warehouse location will go negative Call mess( 578)
See Also
MessBox Statement, Messf Statement, MessResponse Function
Microsoft Dynamics SL API Function Calls 113
MessBox Statement
Displays a message and waits for the user to choose a button.
Syntax
Call MessBox( Msg, Type, Title)
Remarks
The standard Visual Basic MsgBox statement should not be used in applications developed with Microsoft SL SDK in order
to avoid conflicts with other utilities such as Cut/Copy/Paste and Transaction Import. These utilities have built-in
sophistication to respond to messages from the underlying application during the particular operation being performed such
as paste or import. However, this automated functionality does not apply to messages displayed using the standard Visual
Basic MsgBox statement. The MessBox statement has been provided to facilitate similar functionality to the standard
Visual Basic MsgBox statement with the exception that MessBox
does not conflict with other Microsoft Dynamics SL utilities. The MessResponse function can be used to determine which
button was chosen by the user to close the message box. The MessBox statement uses the following arguments:
Type Integer Numeric value controlling the icon style, buttons to be displayed as well as which
button is the default button
Title String Text to display in the title bar of the message dialog box
Example
Dim FactAmt#
FactAmt = GetObjectValue("cannmemo2")
End If
See Also
Mess Statement, Messf Statement, MessResponse Function
114 Customization Manager Reference Visual Basic for Applications
Messf Statement
Formats a message from the message file with replaceable parameters and then displays it and waits for the user to
choose a button.
Syntax
Call Messf( MsgNumber, Parm1Str, Parm2Str, Parm3Str, Parm4Str, Parm5Str, Parm6Str)
Remarks
During installation, an ASCII text file called Messages.csv is copied to the Microsoft Dynamics SL program directory. This
file contains all messages relating to the Microsoft Dynamics SL product, including all independently developed
applications created with Microsoft SL SDK. Each message has, among other things, a message number. The message
can also contain up to six replaceable parameters by placing a %s at the appropriate point(s) within the actual message
text. A particular message can be subsequently displayed to the screen by merely passing its associated message number
to the Messf statement along with data values for each replaceable parameter. The Mess statement should be used if the
actual text of the message does not contain replaceable parameters. The MessResponse function can be used to
determine which button was chosen by the user to close the message box.
The standard Visual Basic MsgBox statement should not be used in applications developed with Microsoft SL SDK in order
to avoid conflicts with other utilities such as Cut/Copy/Paste and Transaction Import. These utilities have built-in
sophistication to respond to messages from the underlying application during the particular operation being performed such
as paste or import. However, this automated functionality does not apply to messages displayed using the standard Visual
Basic MsgBox statement. The MessBox statement has been provided to facilitate similar functionality to the standard
Visual Basic MsgBox statement with the exception that MessBox
does not conflict with other Microsoft Dynamics SL utilities. The Messf statement
uses the following arguments:
Parm2Str String Data value for the second replaceable parameter. Blank if the message text
contains only one replaceable parameter.
Parm3Str String Data value for the third replaceable parameter. Blank if the message text contains less
than three replaceable parameters.
Parm4Str String Data value for the fourth replaceable parameter. Blank if the message text contains less
than four replaceable parameters.
Parm5Str String Data value for the fifth replaceable parameter. Blank if the message text contains less
than five replaceable parameters.
Parm6Str String Data value for the sixth replaceable parameter. Blank if the message text contains less
than six replaceable parameters.
Microsoft Dynamics SL API Function Calls 115
Each record (message) contained within the Messages.csv file contains the following fields separated by a comma:
Message Number Message number which is required by most of the message APIs such as Messf.
Category 0 for all messages. All independently developed applications must also use 0.
Record Type S for messages created and maintained by Microsoft. Independent developers should
not use S for their new messages since they could be deleted or modified by Microsoft.
Unattended Default Button This value is used by Transaction Import to respond to messages
displayed by the underlying application during the import operation.
Message Text Actual text of the message. Replaceable parameters appear as %s. For example: My
first name is %s and my last name is %s.
The Box Type field within the Messages.csv file can have the following values:
16 Stop OK OK
48 Exclamation OK OK
64 Information OK OK
33 Question OK / Cancel OK
Example
The Payroll modules Manual Check Entry ( 02.040.00) screen uses the following code to warn the user of the fact that a
batch is out of balance.
Message number 818 is the actual message displayed and its associated text in the message file reads, Batch is out of
balance by %s. Do you want to edit? This particular message also displays a Yes button and a No button in the message
box. The MessResponse function is subsequently called to determine which of these two buttons the user actually selected
to close the message box.
'Make sure that the batch itself is in balance with the documents.
Call ApplSetFocus(cCtrlTot)
116 Customization Manager Reference Visual Basic for Applications
End If
End If
See Also
Mess Statement, MessBox Statement, MessResponse Function
Microsoft Dynamics SL API Function Calls 117
MessResponse Function
Returns the button chosen by the user to close the last message box displayed using the Mess, Messf or MessBox statements.
Syntax
ButtonId = MessResponse()
Remarks
The MessResponse function returns one of the following symbolic constants declared in the VBTools_VBA module:
Example
Dim Response% Dim WSheet As Object
Call MessBox("Display Excel During Execution?", MB_YESNO, " Message") Response = MessResponse()
DoEvents
'Start Microsoft Excel and create the object. Set WSheet = CreateObject("Excel.Sheet")
See Also
Mess Statement, Messf Statement
118 Customization Manager Reference Visual Basic for Applications
mFindControlName Function
Returns a list of control names present in the current application.
Syntax
ControlName = mFindControlName( FirstFlag)
Remarks
The mFindControlName function is used to return the first and subsequent control names in tab index order. This function
is useful in cases where you wish to write code that is generic but needs to rely on specific control names. By writing
generic versus screen specific code, you can re-use it more often. This function would most often be used in cases where
you wish to programmatically cycle through all controls within a screen and set specific properties based on certain
characteristics (such as background color or ToolTip text).
Note: On controls that are added by Customization Manager, the Tab Index property is set to
900. This value may optionally be changed and would be desirable to assure expected tab order results. However, if
controls that have identical tab index orders are inserted, mFindControlName finds these controls in the order that they
were created.
FirstFlag Integer 1 = Indicates finding the first control (that is, the control whose Tab Index property is
zero)
0 = Indicates finding the next control in Tab Index order
Example
This example cycles through all controls to determine which ones have a PV property. If a control has a PV
property, its ToolTipText property is set to indicate that F3 lookup is available.
Dim CtlName As String, SResult As String ' Find the first control on the screen
' Get the PV property to determine F3 (inquiry) serr1 = GetProp(CtlName, "PV", SResult) If
' Set the tooltiptext property if it is not in use SResult = "Press F3 for list of Possible Values." Call
Wend
Microsoft Dynamics SL API Function Calls 119
This example cycles through all controls to determine which ones have a BlankErr property of True. These would be
required fields. If a control has a BlankErr property of True, its background color is set to blue to provide a visual
indication that it is required.
Dim CtlName As String, SResult As String ' Find the first control on the screen
' Get the 'blankerr' property to determine required controls. serr1 = GetProp(CtlName, "Blankerr", iresult) If serr1 = 0 And
' Blankerr property found and control is required. serr1 = GetProp(CtlName, "BackColor", SResult)
If serr1 = 0 Then
lresult = &HFFFF80
Wend
120 Customization Manager Reference Visual Basic for Applications
MFirst Function
Move to the first record in a designated memory array.
Syntax
RecFetch = MFirst( MemHandle, RecMaintFlg)
Remarks MFirst moves to the first record of a specified memory array and copies the contents of the array record into
the data structure(s) previously specified in the VBA_MOpen function call used to originally open the relevant memory
array. When this call is used on a memory array associated with an SAFGrid control (memory arrays opened
automatically), an MDisplay call will be necessitated to properly synchronize the
RecMaintFlg Integer Status of the memory array record (assuming it was successfully fetched). the
VBTools_VBA module contains the following symbolic constants defining possible
memory array record status values: INSERTED, UPDATED and NOTCHANGED
See Also
MLast Function, MNext Function, MPrev Function
MGetLineStatus Function
Returns the line status of the current record in the designated memory array.
Syntax
RecMaintFlg = MGetLineStatus( MemHandle)
Remarks
The MGetLineStatus function allows the application to retrieve the status of the current memory array record at
any time. The MGetLineStatus function uses the following arguments:
See Also
MSetLineStatus Function
Microsoft Dynamics SL API Function Calls 121
MGetRowNum Function
Returns the row/record number of the current record in the designated memory array.
Syntax
CurrRecNbr = MGetRowNum( MemHandle)
Remarks
The MGetRowNum function uses the following arguments:
See Also
MRowCnt Function, MSetRowNum Statement
122 Customization Manager Reference Visual Basic for Applications
MInsert Statement
Insert a new record into a designated memory array.
Syntax
Call Minsert( MemHandle)
Remarks MInsert is used to add a new record to a memory array. This is accomplished by copying the contents of all
data structures previously associated with the designated memory array into a new memory array record. Data
structures are associated with a memory array in the
VBA_MOpen function call used to originally open the relevant memory array. The new memory array record will have a
line status of INSERTED. When this call is used on a memory array associated with an SAFGrid control (memory arrays
opened automatically), an MDisplay call will be necessitated to properly synchronize the
Example
This example illustrates how records can be inserted into a memory array under program control.
'Allocate cursor
'Initialize cursor with a SQL statement and immediately fetch first record
SqlStr = "Select * from Account order by Acct" Account_Fetch = SqlFetch1(CSR_Account, SqlStr, bAccount, Len(bAccount))
'Read through all subsequent Account records, inserting each one into 'the memory array.
While( Account_Fetch = 0)
Wend
Microsoft Dynamics SL API Function Calls 123
See Also
MDelete Function, MSetLineStatus Function, MUpdate Statement, VBA_MOpen Functions
124 Customization Manager Reference Visual Basic for Applications
MKey Statement
Define a key field for a previously opened memory array.
Syntax
Call MKey( MemHandle, KeySegmentNbr, TableDotFieldName, Ascending)
Remarks
Occasionally a program will need the ability to easily locate a particular record within a memory array based on one or
more key field values. The MKeyFind function can be used to accomplish this goal assuming the sort order for the memory
array has been previously defined. Memory arrays associated with an SAFGrid control automatically have their sort order
initialized based on the key field control(s) contained within the grid (notated by a ,k in the levels property of the controls).
All other memory arrays must have their sort order explicitly defined via one of several different methods. Each of the
methods to define a key field, such as MKey, MKeyFld, MKeyOffset, and MSetRowNum, vary primarily in the way they
acquire detailed information on a key field such as datatype, size and byte offset within a user-defined datatype. The MKey statement
is the simplest and most common of all these methods to define a memory array key field. MKey is so simple because the
system will automatically determine the requisite key field information for the TableDotFieldName based both on the VBA_SetAddr
call for the relevant table and its corresponding data dictionary information in the database. The two restrictions of the MKey
method are that it can only be used for fields whose table exists in the database (as opposed to a memory variable
existing only within Visual Basic code) and a VBA_SetAddr call must have already been issued for the relevant table.
Multi-segment keys can be defined by successive calls to MKey with different KeySegmentNbr
KeySegmentNbr Integer Memory array key segment whose key field is being defined. The first key
segment number is always zero. Multi-segment keys must have contiguous
key segment values such as 0 and 1 as opposed to 0 and 3. The maximum
allowable number of key segments is five.
TableDotFieldName String Name of the designated key field in a Table.FieldName format such as
Account.Acct.
Ascending Integer True if the key segment should be sorted ascending. False to implement a
descending sort sequence for the key segment currently being defined.
Example
This example illustrates how to open a memory array and define multiple key fields.
Dim Mem_ValEarnDed As Integer
"", 0)
Microsoft Dynamics SL API Function Calls 125
"bValEarnDed.DedId", True)
See Also
MKeyFind Function, MKeyFld Statement, MKeyOffset Statement, MSetRowNum Statement, MSort Statement,
VBA_MOpen Functions
126 Customization Manager Reference Visual Basic for Applications
MKeyFind Function
Find a specific record in a sorted memory array based on designated key field values.
Syntax
RecFetch = MKeyFind( MemHandle, KeySeg1Val, KeySeg2Val, KeySeg3Val, KeySeg4Val, KeySeg5Val)
Remarks
Occasionally a program will need the ability to easily locate a particular record within a memory array based on one or
more key field values. The MKeyFind function can be used to accomplish this goal assuming the sort order for the memory
array has been previously defined. Memory arrays associated with an SAFGrid control automatically have their sort order
initialized based on the key field control(s) contained within the grid (notated by a ,k in the levels property of the controls).
All other memory arrays must have their sort order explicitly defined via one of several different methods. Each of the
methods to define a key field, such as MKey, MKeyFld, MKeyOffset, and MSetRowNum, vary primarily in the way they
acquire detailed information on a key field such as datatype, size and byte offset within a user-defined datatype.
If a record whose key fields exactly match the KeySeg?Val arguments does not exist, the system positions to the closest
match. It will however still return a NOTFOUND to the application. The MKeyFind function uses the following arguments:
KeySeg1Val Integer, Double or Desired value for the first key segment.
String
KeySeg2Val Integer, Double or Desired value for the second key segment. PNULL if the memory array only has one key
String segment.
KeySeg3Val Integer, Double or Desired value for the third key segment. PNULL if the memory array has less than three
String key segments.
KeySeg4Val Integer, Double or Desired value for the fourth key segment. PNULL if the memory array has less than four
String key segments.
KeySeg5Val Integer, Double or Desired value for the fifth key segment. PNULL if the memory array has less than five
String key segments.
Example
This example illustrates how to open a memory array, load the entire chart of accounts into the newly-created array,
and then find a specific account record.
'Allocate cursor
'Initialize cursor with a SQL statement and immediately fetch first record
SqlStr = "Select * from Account order by Acct" Account_Fetch = SqlFetch1(CSR_Account, SqlStr, bAccount, Len(bAccount))
'Read through all subsequent Account records, inserting each one into 'the memory array.
While( Account_Fetch = 0)
Wend
See Also
MKey Statement, MKeyFld Statement, MKeyOffset Statement, MSetRow Statement, MSetRowNum
Statement, MSort Statement, VBA_MOpen Functions
128 Customization Manager Reference Visual Basic for Applications
MKeyFld Statement
Define a key field for a previously opened memory array.
Syntax
Call MKeyFld( MemHandle, KeySegmentNbr, TableDotFieldName, bTable, Ascending)
Remarks
Occasionally a program will need the ability to easily locate a particular record within a memory array based on one or
more key field values. The MKeyFind function can be used to accomplish this goal assuming the sort order for the memory
array has been previously defined. Memory arrays associated with an SAFGrid control automatically have their sort order
initialized based on the key field control(s) contained within the grid (notated by a ,k in the levels property of the controls).
All other memory arrays must have their sort order explicitly defined via one of several different methods. Each of the
methods to define a key field, such as MKey, MKeyFld, MKeyOffset, and MSetRowNum, vary primarily in the way they
acquire detailed information on a key field such as datatype, size and byte offset within a user-defined datatype. The MKeyFld
method is similar to the MKey method except that it does not require a
KeySegmentNbr Integer Memory array key segment whose key field is being defined. The first key
segment number is always zero. Multi-segment keys must have contiguous
key segment values such as 0 and 1 as opposed to 0 and 3. The maximum
allowable number of key segments is five.
TableDotFieldName String Name of the designated key field in a Table.FieldName format such as
Account.Acct.
bTable User-defined Memory array table structure containing the designated key field. This table
datatype structure must also have been previously passed to the VBA_MOpen call.
Ascending Integer True if the key segment should be sorted ascending. False to implement a
descending sort sequence for the key segment currently being defined.
Example
This example illustrates how to open a memory array and define multiple key fields.
Dim Mem_ValEarnDed As Integer
Call MKeyFld( Mem_ValEarnDed, 0, "bValEarnDed.EarnTypeId", bValEarnDed, True) Call MKeyFld( Mem_ValEarnDed, 1, "bValEarnDed.DedId",
bValEarnDed, True)
Microsoft Dynamics SL API Function Calls 129
See Also
MKey Statement, MKeyFind Function, MKeyOffset Statement, MSetRowNum Statement, MSort Statement, VBA_MOpen
Functions
130 Customization Manager Reference Visual Basic for Applications
MKeyOffset Statement
Define a key field for a previously opened memory array.
Syntax
Call MKeyOffset( MemHandle, KeySegmentNbr, bTable, KeyFldByteOffset, KeyFldDataType, KeyFldDataLength,
Ascending)
Remarks
Occasionally a program will need the ability to easily locate a particular record within a memory array based on one or
more key field values. The MKeyFind function can be used to accomplish this goal assuming the sort order for the memory
array has been previously defined. Memory arrays associated with an SAFGrid control automatically have their sort order
initialized based on the key field control(s) contained within the grid (notated by a ,k in the levels property of the controls).
All other memory arrays must have their sort order explicitly defined via one of several different methods. Each of the
methods to define a key field, such as MKey, MKeyFld, MKeyOffset, and MSetRowNum, vary primarily in the way they
acquire detailed information on a key field such as datatype, size and byte offset within a user-defined datatype. The MKeyOffset
method is the most flexible method of defining memory array key fields but it is also the most detailed to code. It is
designed to facilitate the definition of a key field that does not exist in the database and therefore has no correlated data
dictionary information in the database. This situation can occur if one of the user-defined datatypes in a memory array is
only declared within Visual Basic and does not exist within the database. In such a case, the system has no way of
determining the byte offset from the beginning of the structure for any particular field, the field datatype nor the length of
the field. The MKeyOffset statement allows the developer to explicitly pass all of this detailed information relating to the
designated key field since it does not exist in the SQL data dictionary. Multi-segment keys can be defined by successive
calls to MKeyOffset with different
KeySegmentNbr Integer Memory array key segment whose key field is being defined. The first key segment
number is always zero. Multi-segment keys must have contiguous key segment
values such as 0 and 1 as opposed to 0 and 3. The maximum allowable number of
key segments is five.
bTable User-defined Memory array table structure containing the designated key field. This table structure
datatype must also have been previously passed to the
VBA_MOpen call.
KeyFldByteOffset Integer This argument is designed to help the system locate the first byte of the designated
key field. The system will already know the memory location of the first byte of the
entire user-defined datatype via the bTable argument. The byte offset tells the
system how far the first byte of the designated key field is offset from the first byte of
the entire user-defined datatype. If the designated key field is the first field in the
user-defined datatype then a value of zero should be passed.
Microsoft Dynamics SL API Function Calls 131
KeyFldDataLength Integer Size of the designated key field. For example, LenB(bTable.KeyFld). Note: It is
critical to use LenB() instead of
Len() for all non-null table length parameters.
Ascending Integer True if the key segment should be sorted ascending. False to implement a
descending sort sequence for the key segment currently being defined.
Example
The following example illustrates a memory array containing only selected fields from the Employee table that is
nevertheless sorted by Employee ID. By only storing selected fields in the memory array, much less memory will be
consumed for each record within the memory array.
Since not all fields in the Employee table are contained within the Employee_SelFld user- defined datatype, the data
dictionary information in the SQL database corresponding to the standard Employee table is not usable by the system for
purposes of determining the required key field information. Consequently, MKeyOffset must be utilized to implement
sorting on the Employee ID key field.
The example code below declares the user-defined datatype containing only selected fields from the Employee table.
Notice that the Name field is being deliberately declared before the EmpId field to further illustrate the complete flexibility
of MKeyOffset.
Type Employee_SelFld
Name As String * 30
EmpId As String * 10
End Type
Code to open a memory array for the bEmployee_SelFld user-defined datatype and define Employee ID as the key
field:
Dim Mem_Employee_SelFld As Integer
bEmployee_SelFld, 30,
Code to load the memory array with relevant selected fields for all employees in the database (notice that the order of the
fields in the SQL Select statement corresponds to the order of the fields in the Employee_SelFld user-defined datatype):
'Allocate a cursor
'Initialize cursor with a SQL statement and immediately fetch 'the first record
SqlFetch1(CSR_Employee_SelFld, SqlStr,
bEmployee_SelFld, LenB(bEmployee_SelFld))
'Read through all subsequent Employee records, inserting each one into 'the memory array.
While(Employee_SelFld_Fetch = 0)
Employee_SelFld_Fetch = SFetch1(CSR_Employee_SelFld,
bEmployee_SelFld, LenB(bEmployee_SelFld))
Wend
See Also
MKey Statement, MKeyFind Function, MKeyFld Statement, MSetRowNum Statement, MSort Statement,
VBA_MOpen Functions
Microsoft Dynamics SL API Function Calls 133
MLast Function
Move to the last record in a designated memory array.
Syntax
RecFetch = MLast( MemHandle, RecMaintFlg)
Remarks MLast moves to the last record of a specified memory array and copies the contents of the array record into
the data structure(s) previously specified in the VBA_MOpen function call used to originally open the relevant memory
array. When this call is used on a memory array associated with an SAFGrid control (memory arrays opened
automatically), an MDisplay call will be needed to properly synchronize the grid appearance with the memory array. The
MLast function uses the following arguments:
RecMaintFlg Integer Status of the memory array record (assuming it was successfully fetched). the
VBTools_VBA module contains the following symbolic constants defining possible
memory array record status values: INSERTED, UPDATED and NOTCHANGED
See Also
MFirst Function, MNext Function, MPrev Function
134 Customization Manager Reference Visual Basic for Applications
MLoad Statement
Load a memory array with all records returned from the database by an SQL statement.
Syntax
Call MLoad( MemHandle, Cursor)
Remarks
There are two ways to load data directly from the database into a memory array. The most obvious method is to insert one
record at a time into the memory array until no additional records are returned from the database. A simpler method is to
load the entire array via a single call to the MLoad statement. The only requirement is that the Cursor passed as a
parameter to the MLoad statement must already be initialized with an SQL Select statement or stored procedure so it is
ready to begin returning data. Passing the SQL Select statement or stored procedure, along with any necessary
parameters, to the Sql statement can initialize the cursor. The MLoad statement uses the following arguments:
Cursor Integer SQL database cursor. This cursor must have already been initialized with an SQL
Select statement or stored procedure.
Example
The following example illustrates a memory array containing only selected fields from the Employee table that is
nevertheless sorted by Employee ID. By only storing Employee fields in the memory array, less memory is consumed for
each record within the memory array. Since not all fields in the Employee table are contained within the
Employee_SelFld user- defined datatype, the data dictionary information in the SQL database corresponding to the
standard Employee table is not usable by the system for purposes of determining the required key field information.
Consequently, MKeyOffset must be utilized to implement sorting on the Employee ID key field.
The following code can be used to declare the user-defined datatype containing only selected fields from the Employee
table. Notice that the Name field is being deliberately declared before the EmpId field to further illustrate the complete
flexibility of MKeyOffset:
Type Employee_SelFld
Name As String * 30
Code to open a memory array for the bEmployee_SelFld user-defined datatype and define Employee ID as the key
field:
Dim Mem_Employee_SelFld As Integer
Code to load the memory array with relevant selected fields for all employees in the database (notice that the order of the
fields in the SQL Select statement correspond to the order of the fields in the Employee_SelFld user-defined datatype):
'Allocate a cursor
'Initialize cursor with a SQL statement and immediately fetch 'the first record
SqlFetch1(CSR_Employee_SelFld, SqlStr,
bEmployee_SelFld, Len(bEmployee_SelFld))
'Read through all subsequent Employee records, inserting each one into the 'memory array.
While(Employee_SelFld_Fetch = 0)
Employee_SelFld_Fetch = SFetch1(CSR_Employee_SelFld,
bEmployee_SelFld, Len(bEmployee_SelFld))
Wend
See Also
Sql Statement
136 Customization Manager Reference Visual Basic for Applications
MNext Function
Move to the next record in a designated memory array.
Syntax
RecFetch = MNext( MemHandle, RecMaintFlg)
Remarks MNext moves to the next record of a specified memory array and copies the contents of the array record into
the data structure(s) previously specified in the VBA_MOpen function call used to originally open the relevant memory
array. When this call is used on a memory array associated with an SAFGrid control (memory arrays opened
automatically), an MDisplay call will be necessitated to properly synchronize the
RecMaintFlg Integer Status of the memory array record (assuming it was successfully fetched). the
VBTools_VBA module contains the following symbolic constants defining possible
memory array record status values: INSERTED, UPDATED and NOTCHANGED
See Also
MFirst Function, MLast Function, MPrev Function
Microsoft Dynamics SL API Function Calls 137
MPrev Function
Move to the previous record in a designated memory array.
Syntax
RecFetch = MPrev( MemHandle, RecMaintFlg)
Remarks MPrev moves to the previous record of a specified memory array and copies the contents of the array record into
the data structure(s) previously specified in the VBA_MOpen function call used to originally open the relevant memory
array. When this call is used on a memory array associated with an SAFGrid control (memory arrays opened
automatically), an MDisplay call will be necessitated to properly synchronize the
RecMaintFlg Integer Status of the memory array record (assuming it was successfully fetched). the
VBTools_VBA module contains the following symbolic constants defining possible
memory array record status values: INSERTED, UPDATED and NOTCHANGED
See Also
MFirst Function, MLast Function, MNext Function
138 Customization Manager Reference Visual Basic for Applications
MRowCnt Function
Returns the number of records in a designated memory array.
Syntax
NumRecs = MRowCnt( MemHandle)
Remarks
The MRowCnt function uses the following arguments:
Example
Global ArrayHandle%, Rows%
See Also
VBA_MOpen Functions
MSet Statement
Explicitly set the value of a particular control for every record in its corresponding SAFGrid
control.
Syntax
Call MSet( Control, NewDataValue)
Remarks
The MSet statement uses the following arguments:
NewDataValue String New data value for the Record.FieldName associated with the designated
Control. The data value must be in a string format.
See Also
MSetProp Statement
Microsoft Dynamics SL API Function Calls 139
MSetLineStatus Function
Set the line status of the current record in the designated memory array.
Syntax
RetVal = MSetLineStatus( MemHandle, NewLineStatus)
Remarks
Each record within a memory array has its own line status such as INSERTED, UPDATED or NOTCHANGED. The
system automatically modifies the line status based on the type of activity last performed on any particular memory array
record. For example if a record is inserted into a memory array using MInsert, then the status of that new memory array
record will automatically be set to INSERTED. Occasionally, however, the application may need to assign a specific line
status to a particular memory array record. In such cases the MSetLineStatus
RecMaintFlg Integer New status of the current memory array record. the VBTools_VBA module contains the
following symbolic constants defining possible memory array record status values:
INSERTED, UPDATED and NOTCHANGED.
Example
This example illustrates how to load a memory array from the database, and at the same time, force the line status of all
newly-inserted memory array records to be NOTCHANGED.
'Allocate cursor
'Initialize cursor with a SQL statement and immediately fetch first record
SqlStr = "Select * from Account order by Acct" Account_Fetch = SqlFetch1(CSR_Account, SqlStr, bAccount, Len(bAccount))
140 Customization Manager Reference Visual Basic for Applications
'Read through all subsequent Account records, inserting each one into 'the memory array.
While( Account_Fetch = 0)
Wend
See Also
MGetLineStatus Function, MInsert Statement, MUpdate Statement
Microsoft Dynamics SL API Function Calls 141
MSetProp Statement
Set the value of a particular property for both the designated form-view control as well as its associated SAFGrid control.
Syntax
Call MSetProp( Control, PropertyName, NewPropValue)
Remarks
At runtime, each column of an SAFGrid control is associated with an underlying (form-view) Microsoft SL SDK custom
control. The MSetProp statement can be used to modify a property setting for both the underlying control as well as the
relevant column in the associated grid. For example, an entire column can be disabled using the MSetProp statement.
If the application wants to modify property values on a line by line basis, as opposed to an entire column, then it will
need to manage the property settings using calls to the SetProp
statement from within the LineGotFocus event of each individual detail line. The MSetProp statement
uses the following arguments:
NewPropValue String or New property value. The actual datatype varies based on the property being referenced.
Integer
Example
'Disable the ExtRefNbr Column Call MsetProp(" cextrefnbr", PROP_ENABLED, False) 'Enable
See Also
BlankErr Property, Enabled Property, Heading Property, Mask Property, Min Property, Max Property, SetProp
Statement, Visible Property
142 Customization Manager Reference Visual Basic for Applications
MSetRowNum Statement
Set the current row/record number of a designated memory array.
Syntax
Call MSetRowNum( MemHandle, NewCurrRecNbr)
Remarks
An application can jump to a specific memory array record via either the MKeyFind function or the MSetRowNum
statement. MSetRow jumps to a specific record number whereas MKeyFind locates the record with designated key field
values. The MSetRowNum statement uses the following arguments:
See Also
MGetRowNum Function, MKeyFind Function
MSort Statement
Sort data contained within an existing memory array based upon predefined key fields.
Syntax
Call MSort( MemHandle)
Remarks
This statement will sort all existing records within the designated memory array based upon key fields previously
defined using one of the MKey, MKeyFld, MkeyOffset, or MSetRowNum statements.
If the data within the memory array is initially loaded and maintained in the proper order, a call to MSort will not be
necessary. MSort only needs to be called if one or more records within the memory array are not in an order consistent
with the previously defined key fields. When the data is out of order, MKeyFind will not work properly since it assumes that
the data within the memory array is consistent with the predefined sort sequences.
Memory arrays associated with an SAFGrid control require an MDisplay call to redisplay the grid, subsequent to
calling MSort.
See Also
MKey Statement, MKeyFind Function, MKeyOffset Function, MSetRowNum
Statement,VBA_MOpen Functions
Microsoft Dynamics SL API Function Calls 143
MUpdate Statement
Update the current memory array record of a designated memory array with new data values.
Syntax
Call MUpdate( MemHandle)
Remarks MUpdate is used to update an existing record of a specified memory array. This is accomplished by copying the
new contents of all data structures previously associated with the designated memory array over the existing memory
array record. Data structures are associated with a memory array in the VBA_MOpen function call used to originally open
the relevant memory array. If the memory array record had a line status of INSERTED prior to the
MUpdate call then the line status will remain INSERTED. In all other cases, the memory array record will have a line
status of UPDATED. The MUpdate statement uses the following arguments:
See Also
MDelete Function, MInsert Statement, MSetLineStatus Function, VBA_MOpen Functions
144 Customization Manager Reference Visual Basic for Applications
NameAltDisplay Function
Displays a string field with swap character suppressed.
Syntax
StrVar = NameAltDisplay ( FieldName)
Remarks
To accommodate alternate sorting by name, Microsoft Dynamics SL stores most address and name fields based on where
the @ is placed in the name. For example, in order for The Jones Company to sort with the J s, this name must be
entered as The @Jones Company. The software then stores this entry as Jones Company~The. If you wish to
subsequently retrieve and/or manipulate this field in VBA code, this function flips the name and suppress the ~ and @. In
this example, Jones Company~The as stored in the database is displayed as The Jones Company. The NameAltDisplay function
uses the following arguments:
Example
Dim SwapName$, OrigName$ OrigName = GetObjectValue("cname") Call
See Also
GetObjectValue Function, SetObjectValue Function
Microsoft Dynamics SL API Function Calls 145
PasteTemplate Function
Paste information from the designated template into the current application.
Syntax
RetVal = PasteTemplate( TemplateID)
Remarks
The Template feature makes it possible to store data from the current screen and subsequently paste that data into the
same screen at a later time. Templates can be saved to the database programmatically using the SaveTemplate statement
as well as via the Template menu item on the Edit menu. Once a template has been created it can be pasted into its source
application under program control using the PasteTemplate function as well as via the
Template menu item on the Edit menu. The PasteTemplate statement uses the
following arguments:
TemplateID String ID of the template whose information is to be pasted into the current Microsoft SL SDK
application screen.
See Also
SaveTemplate Statement
PeriodCheck Function
Verify whether or not a period string in YYYYPP format represents a valid fiscal period.
Syntax
RetVal = PeriodCheck( PeriodString)
Remarks
The PeriodCheck function uses the following arguments:
Example
'Example placed in Chk event of a String user field 'The mask property on this field is Custom mask Type, 99-9999 Dim
Year$, Period$ Year = Right$(chkstrg, 4) Period = Left$(chkstrg, 2) serr = PeriodCheck( Year + Period)
146 Customization Manager Reference Visual Basic for Applications
PeriodMinusPeriod Function
Return the number of periods between two fiscal periods.
Syntax
NbrPeriods = PeriodMinusPeriod( PerNbr1, PerNbr2)
Remarks
The PeriodMinusPeriod function uses the following arguments:
Note: This function will use the number of periods in a fiscal year, as specified in the GLSetup record, in order to derive
an accurate result.
Example
Dim Period1$, Period2$ Dim NumPers%
Period1, Period2)
See Also
PeriodPlusPerNum Function
Microsoft Dynamics SL API Function Calls 147
PeriodPlusPerNum Function
Add a designated number of periods to an existing fiscal period.
Syntax
ResultingPerNbr = PeriodPlusPerNum( CurrPerNbr, NbrPeriodsToAdd)
Remarks
The PeriodPlusPerNum function uses the following arguments:
NbrPeriodsToAdd Integer Number of fiscal periods to add to CurrPerNbr. Negative values are supported.
Note: This function will use the number of periods in a fiscal year, as specified in the GLSetup record, in order to derive
an accurate result.
Example
'Increment PerPost to the next fiscal period Dim NewPeriod$, PeriodToPost$,
NumberOfPeriods% NumberOfPeriods = 1
See Also
PeriodMinusPeriod Function
148 Customization Manager Reference Visual Basic for Applications
PVChkFetch Functions
Retrieve a composite record from the database using an SQL statement from the PV property of an SAFMaskedText control.
Syntax
RetVal = PVChkFetch1( Ctrl, Cursor, SQLParmValue, bTable1, bTable1Length) RetVal = PVChkFetch4( Ctrl,
Cursor, SQLParmValue, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length, bTable4,
bTable4Length)
RetVal = PVChkFetch8( Ctrl, Cursor, SQLParmValue, bTable1, bTable1Length, bTable2, bTable2Length, bTable3,
bTable3Length, bTable4, bTable4Length, bTable5, bTable5Length, bTable6, bTable6Length, bTable7, bTable7Length,
bTable8, bTable8Length)
Remarks
Each SAFMaskedText control has a PV property which can contain an SQL statement or stored procedure name. These
functions can be used to fetch a composite record instance based on the SQL text from the PV property of the control
specified in the Ctrl parameter. These functions are not applicable if the PV property does not contain either an SQL
statement or stored procedure name.
PVChkFetch1 is designed for SQL statements returning data from a single table. For more advanced SQL statements
having one or more table joins either PVChkFetch4 or PVChkFetch8
can be used. The PVChkFetch1 function uses the following arguments ( PVChkFetch4 and PVChkFetch8
respectively have four and eight table structures and corresponding lengths. PNULL should be passed for unused table
structure parameters as well as a corresponding length of zero such as PNULL, 0)
Ctrl Control Control containing the PV property to be used as the SQL statement. Can
optionally be PNULL if the call is made within the Chk event of the control
whose PV property is being used.
SQLParmValue String Key value passed as the last parameter to the restriction clause of the PV
SQL statement.
bTable1 User-defined Table structure corresponding to the primary table in the PV SQL statement.
datatype
Example
The following example illustrates the usage of PVChkFetch1 in the Chk event of a Payroll Work Location ID control. Since
PNULL is passed for the control parameter the SQL statement in the PV property of the cWrkLocId control is used. The ID
entered by the user is passed to the Chk event as chkstrg. By sending this value to PVChkFetch1, it will be used as the
last parameter to the restriction clause of the PV SQL statement.
End Sub
See Also
DBNavFetch Functions
150 Customization Manager Reference Visual Basic for Applications
SaveTemplate Statement
Save information from the current application to a designated template.
Syntax
Call SaveTemplate( TemplateID, Description, AppliesToUserID, IncludeLowerLevels, StartingLevelNbr)
Remarks
The Template feature makes it possible to store data from the current screen and subsequently paste that data into the
same screen at a later time. These timesaving templates can be saved to the database programmatically using the SaveTemplate
statement as well as via the
Template menu item on the Edit menu. Each template can contain complete transactions and entities or individual fields
selected by the user. Relative date and period features allow a template to paste data relative to the current date and fiscal
period. Templates can be designated as private to a specific user or marked public for availability to all users. Templates
are stored in the system database and therefore they are independent of any particular application database.
Unless otherwise specified, all date and period values pasted from a template will be equal to the Microsoft Dynamics SL
business date, located on the File menu, and the current period for the module. To override this default action, the user
entering data for the template must specify a new relative date or period value for each desired field. This is done
immediately before saving a template. Specifying a relative date or period value for a field contained in grid detail lines will
change the template value of that field for all detail lines. Relative values can be defined by selecting the pertinent date or
period field and pressing F2 to start the Relative Date or Relative Period window, whichever is appropriate. The SaveTemplate
statement uses the following arguments:
AppliesToUserID String User ID to which the template applies. By default, the template will be Public if
AppliesToUserID is left blank.
IncludeLowerLevels Integer False if only data for the StartingLevelNbr is to be saved to the template.
Otherwise data for lower levels, in addition to StartingLevelNbr, will also be saved
to the template.
StartingLevelNbr Integer Number of the first application level for which data is to be saved to the template. For
example on Batch/Document/Detail screens, a value of zero could be passed to start the
save with the Batch level. the VBTools_VBA module contains two symbolic constants
which can also be passed:
CcpSelectedFields Only those fields currently highlighted by the user will be saved to the
template.
CcpAllLevels Data from all application levels will be saved to the template
regardless of the IncludeLowerLevels argument value.
See Also
PasteTemplate Function
Microsoft Dynamics SL API Function Calls 151
SDelete Statement
Delete the current record from a designated table within an existing SQL view.
Syntax
Call SDelete( Cursor, TablesDeletingFrom)
Remarks
A value of *.* can be passed as a table name, meaning that all current records in the existing view will be deleted. Please
note that this call requires that the current record already be fetched via such functions as SqlFetch1 or SFetch1 so that the
designated cursor actually has a current record. The SDelete statement uses the following arguments:
TablesDeletingFrom String Name of each table, in the specified cursors view, from which the current record
is to be deleted. Commas should separate multiple table names.
Example
'Example is deleting in Microsoft Dynamics SL's OnDelete event
'Note that the following fetch been has issued in 'a preceding event prior to the delete call serr1 =
If Level = 0 Then
See Also
SFetch Functions, SqlFetch Functions
152 Customization Manager Reference Visual Basic for Applications
SDeleteAll Function
Delete all records from the designated table(s) within a predefined view.
Syntax
RetVal = SDeleteAll( Cursor, TablesDeletingFrom)
Remarks
Deletes records from some or all of the tables in a view based on the current restrictions. A view must have already been
initialized for the specified cursor via functions such as Sql, SFetch1 or SqlFetch4. If no restriction is specified when the
cursor is initialized, then this call will remove all records from the designated table(s) in the view. The SDeleteAll function
uses the following arguments:
TablesDeletingFrom String Name of each table, in the specified cursors view, from which all records within the
current view are to be deleted. Commas should separate multiple table names. A
value of *.* can be used to delete records from all tables within the view.
Example
The code in this example deletes all vendors that have a zero balance.
Dim SqlStr As String
SqlStr = "Select * from Vendor where CurrBal = 0 and FutureBal = 0" Call Sql(CSR_Vendor_Del, SqlStr)
'Delete all records matching the restriction clause of the SQL statement 'used to initialize the CSR_Vendor_Del cursor.
See Also
SFetch Functions, Sql Statement, SqlFetch Functions
Microsoft Dynamics SL API Function Calls 153
SetBufferValue Statement
Sets an underlying Microsoft Dynamics SL applications data buffer field to a specified value.
Syntax
Call SetBufferValue( bTable.FieldName, Str)
Remarks
If a VBA application issues its own VBA_SetAddr calls it can then reference any of these structures from within code.
However, if the underlying Microsoft Dynamics SL applications structures need to be referenced and these fields are not
represented as objects on the form, this statement allows the VBA application to obtain these values. If the fields were
objects on the form, the VBA application can simply issue SetObjectValue instead. Be aware that usage of this call at
times could compromise the underlying Microsoft Dynamics SL application functionality, especially if a dependent field is
changed. Likewise, the underlying application may change your value if you have set it too early. The SetBufferValue statement
uses the following arguments:
Str String String or string variable that contains the value that your changing the
specific bTable.FieldName to.
Example
Call SetBufferValue(" bGLTran.RefNbr","000099")
See Also
GetBufferValue Statement
154 Customization Manager Reference Visual Basic for Applications
SetDefaults Statement
Set one or more controls to their default value using either their Default Property or Default Event code.
Syntax
RetVal = SetDefaults ( FormObjectName, FieldObjectName)
Remarks
Each data object has both a Default property as well as a Default event. Any particular data object can use one of these
two methods to define a default data value for itself. The system uses these methods any time a particular data object is to
be initialized to its default value. An exhaustive discussion of all the times when this occurs is beyond the scope of the SetDefaults
statement. However, one such time an object is set to its default value is when the application explicitly directs the system
to do so via usage of the SetDefaults statement in reference to the relevant object. The SetDefaults statement can be used
to default all objects in a subform. The Level_SetDefaults statement is functionally equivalent except it can be used to
explicitly default all objects having a particular level number. Since SetDefaults implies a change in the data value of the
designated object, the system marks the object as requiring error checking. The system does not, however, immediately
perform the requisite error checking (for example, it does not immediately fire the Chk event). The error checking is
nevertheless guaranteed to occur prior to any updates to the database. Note that when an application needs to null out a
particular field, perhaps because the field is no longer applicable, it should explicitly do so programmatically and then
redisplay the relevant object using the DispField statement. After the object has been redisplayed, it can then be disabled
using the SetProp statement. The SetDefaults statement should not be used in these cases even if the relevant control has
no Default Property value and no code within Default Event. A developer may well wonder why this caution would be
expressed since the field is, in fact, nulled out when no Default Property or Event code exists and, therefore, the application
appears to work properly during testing. The following code conceptually illustrates how to properly null out and disable a
control that is no longer applicable:
Record.Field = NULL (0 for numeric datatypes , "" for string datatype) Call DispFields("Form1", "cField") Call SetProp ("cField",
PROP_ENABLED, False)
FormObjectName String Form name. Can be "" to include all forms in application.
FieldObjectName String Field name. Can be "" to include all objects in a specific form.
Microsoft Dynamics SL API Function Calls 155
Example
This example fetches from custom table, evaluates the return value, and sets up custom form for entry/edit.
Call DispFields("NewInfo","")
See Also
DispField Statements, SetProp Statement
156 Customization Manager Reference Visual Basic for Applications
SetLevelChg Statement
Set the update status of a specific level.
Syntax
Call SetLevelChg( LevelNbr, Status)
Remarks
Each update level, as defined by the Levels property of the SAFUpdate control, has a corresponding level status flag that is
automatically maintained by the system. The purpose of the level status flag is to facilitate the optimization of database
updates performed in response to Microsoft Dynamics SL toolbar buttons. In general, these flags allow the system to only
perform database updates for update levels which have in fact changed. If no information has changed then no information
needs to be saved.
As previously mentioned, these update flags are automatically maintained by the system. When an existing record is
loaded the flag is set to NOTCHANGED. If any non-key field is subsequently modified then the level status flag for the
corresponding level is set to UPDATED. When a new record is being entered, the level status flag is set to INSERTED.
The SetLevelChg statement allows the application to override the current value a the status flag for a particular level. This
can be useful if a data value is modified programmatically and therefore the system needs to be notified that something has
changed so the corresponding information will actually be saved when the user presses the Save toolbar button. The SetLevelChg
statement uses the following arguments:
Status Integer Level status flag. The following valid values are defined as symbolic constants in the
VBTools_VBA module: INSERTED, UPDATED, NOTCHANGED.
Example
The Payroll modules Earnings Type Maintenance ( 02.270.00) window contains a button to automatically populate the grid
with all deductions. This amounts to inserting records into the grid (that is, into its underlying memory array) under
program control. Since the data is not entered via the user interface by the user, the system needs to be notified that
information at the grid level (LEVEL1 in this case) has been programmatically updated and therefore needs to be saved.
However, such notification only needs to occur if the system is not already aware that data has changed.
'If any records were inserted into the memory array then we need to make 'sure that the level status for the detail level is something other than
See Also
TestLevelChg Function
Microsoft Dynamics SL API Function Calls 157
SetObjectValue Function
Sets a specified object fields value.
Syntax
IntVar = SetObjectValue( ObjectName, Value)
Remarks
This function allows you to set the value of any bound object on the screen. The object must be on the form in order to
set it. If you wish to set a value of a field that is not on the form, you can use the SetBufferValue statement instead.
Note that you can use this function to set disabled and invisible objects that you make invisible or hidden. You cannot set
disabled or invisible standard objects. The Chk event of the object you set is also executed so that all error checking takes
place. The SetObjectValue function uses the following arguments:
ObjectName String Name of the object whose value you wish to set.
Example
Dim CommissionAmount As Double Dim ExtendedAmount As
2000 then
3000 then
CommissionAmount = 3 Else
See Also
GetObjectValue Function, SetBufferValue Statement
158 Customization Manager Reference Visual Basic for Applications
SetProp Statement
Sets the properties of objects at runtime.
Syntax
Call SetProp ( ObjectName, PropertyName, PropertyValue)
Remarks
Allows the application to set property values at runtime. This function should not be used to set default properties. The SetProp
statement uses the following arguments:
The following valid values for the PropertyName argument are defined as symbolic constants in the VBTools_VBA module:
PROP_CAPTION String
PROP_CUSTLIST String
PROP_HEADING String
PROP_MASK String
PROP_MIN String
PROP_MAX String
Example
'Enable push button Call SetProp(" OpenButton", PROP_ENABLED, True) 'Disable push
button Call SetProp(" OpenButton", PROP_ENABLED, False) 'Make an object invisible Call SetProp("
'Example uses a password dialog for setting a field invisible at runtime Dim PassWord$
PassWord = PasswordBox$("Enter the Password Override","Message") ' Get password (case sensitive) If Trim$(PassWord) =
"SYSADMIN" Then
See Also
MSetProp Statement, SetDefaults Function
160 Customization Manager Reference Visual Basic for Applications
SetStatusBarText Statement
Display text in the Application Status Bar.
Syntax
Call SetStatusBarText ( StatusBarText, ToolTip)
Remarks
This function will allow the customization to set the text of the toolbar. The first parameter holds the text to be displayed
in the toolbar, the second holds the text to be displayed in the ToolTip for the left pane of the toolbar. If an empty string
("") is specified for the second parameter, the text (first parameter) will be used for the ToolTip.
Example
This example displays the account description in the application status bar in General Ledger
Journal Transaction ( 01.010.00).
Sub cacct_Chk(chkstrg$, retval%)
SqlStr = "Select * from account where acct = " & chkstrg xRetVal = SqlFetch1(xCursor, SqlStr, bAccount, Len(bAccount))
SFetch Functions
Used to retrieve a composite record from the database based on some pre-defined SQL statement or stored
procedure.
Syntax
RetVal = SFetch1( Cursor, bTable1, bTable1Length) RetVal = SFetch4( Cursor, bTable1, bTable1Length, bTable2,
bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length) RetVal = SFetch8( Cursor, bTable1, bTable1Length,
bTable2, bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length, bTable5, bTable5Length, bTable6,
bTable6Length, bTable7, bTable7Length, bTable8, bTable8Length)
Remarks
In order to fetch information from the server it must first know what tables, records and fields are being queried from a
particular cursor. Consequently the cursor must first be initialized with either an SQL statement or stored procedure via
the use of the Sql statement or the
SqlFetch1, SqlFetch4 or SqlFetch8 functions. Once the database view has been established these functions will retrieve
the next sequential record in the view consistent with the Order By clause of the SQL statement used to initialize the view.
After the last record in the view has been returned all subsequent calls to SFetch1, SFetch4 and SFetch8 will return
NOTFOUND.
SFetch1 is designed for SQL statements returning data from a single table. For more advanced SQL statements having
one or more table joins either SFetch4 or SFetch8 can be used. The SFetch1 function uses the following arguments ( SFetch4
and SFetch8 respectively have four and eight table structures and corresponding lengths. PNULL should be passed for
unused table structure parameters as well as a corresponding length of zero such as PNULL, 0).
bTable1 User-defined Table structure corresponding to the primary table in the SQL statement.
datatype
bTable1Length Integer Size of first table structure. For example, LenB( bTable1). Note: It is critical to use LenB() instead
of Len() for all non-null table length parameters.
Note: SGroupFetch1, SGroupFetch4 or SGroupFetch8 must be used if the SQL statement used to initialize the cursor
contained one or more of the following components:
DISTINCT keyword
GROUP BY clause
HAVING clause
Subqueries
Example
This example links the Inventory table to an existing screen for lookup and navigation only.
(general) declarations: '$include: "inventor.dh"
162 Customization Manager Reference Visual Basic for Applications
Form1_Load
Call VBA_SetAddr(c1, "bInventory", bInventory, Len(bInventory)) Call SqlCursor(c1, NOLEVEL) Dim SqlStmt$
SqlStmt = "Select * from Inventory Where ClassID = 'BOX'Order By ClassID" Call Sql(c1, SqlStmt) serr1 = Sfetch1( c1, bInventory,
'Check LastCost
Wend
See Also
Sql Statement, SqlFetch Functions
Microsoft Dynamics SL API Function Calls 163
SGroupFetch Functions
Used to retrieve a composite record from the database based on some pre-defined SQL statement or stored
procedure containing one or more group aggregate functions and/or clauses.
Syntax
RetVal = SGroupFetch1( Cursor, bTable1, bTable1Length) RetVal = SGroupFetch4( Cursor, bTable1, bTable1Length,
bTable2, bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length) RetVal = SGroupFetch8( Cursor, bTable1,
bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length, bTable5, bTable5Length,
bTable6, bTable6Length, bTable7, bTable7Length, bTable8, bTable8Length)
Remarks
In order to fetch information from the server it must first know what tables, records and fields are being queried from a
particular cursor. Consequently the cursor must first be initialized with either an SQL statement or stored procedure via
the use of the Sql statement.
SGroupFetch1, SGroupFetch4 or SGroupFetch8 are only designed for cases where the SQL statement used to
initialize the cursor contains one or more of the following:
DISTINCT keyword
GROUP BY clause
HAVING clause
Subqueries The logically equivalent SFetch1, SFetch4 and SFetch8 functions should be used if the SQL
statement does not contain any of the above referenced items.
Once the database view has been established these functions will retrieve the next sequential record or data value in the
view consistent with the Order By or Group By clause of the SQL statement used to initialize the view. After the last
record or data value in the view has been returned all subsequent calls to SGroupFetch1, SGroupFetch4 and SGroupFetch8
will return NOTFOUND.
SGroupFetch1 is designed for SQL statements returning data from a single table. For more advanced SQL
statements having one or more table joins either SGroupFetch4 or
SGroupFetch8 can be used. The SGroupFetch1 function uses the following arguments ( SGroupFetch4 and SGroupFetch8
respectively have four and eight table structures and corresponding lengths. PNULL should be passed for unused table
structure parameters as well as a corresponding length of zero such as PNULL, 0).
bTable1 User-defined Table structure corresponding to the primary table or data value in the SQL statement.
datatype
bTable1Length Integer Size of first table structure or data value. For example, LenB( bTable1) or
Len(DoubleVariable). Note: It is critical to use LenB() instead of
Len() for all non-null table length parameters.
164 Customization Manager Reference Visual Basic for Applications
Note: The type and size of the data returned can vary when the SQL statement contains one or more group aggregates.
For the COUNT group aggregate, the data will always be returned as a 4-byte integer (that is, Long Visual Basic datatype).
The MIN and MAX group aggregates always return the same data type and length as the field on which the aggregate is
based. The SUM and AVG group aggregates always return 8-byte floating point values (that is, Double Visual Basic
datatype).
Example
This example retrieves the last voucher date for the current vendor and selects a count of all documents less than the
last voucher date.
Dim SqlStr$
Sdate
DateComp.Val = GetObjectValue("clastvodate")
SqlStr = "Select Count(*) from APDoc Where DocDate < " + Dparm(DateComp) Call Sql(c1, SqlStr) serr1 = sgroupfetch1( c1, CountDoc,
SqlStmt = "Select Sum(QtyOnHand), Sum(TotCost) from ItemSite Where ItemSite.InvtId = @parm1 Order By ItemSite.InvtId" ItemId = GetObjectValue("cinvtid") Call
Sql(c1, SqlStmt)
Call SqlSubst(c1, "parm1", ItemID) Call SqlExec(c1) serr1 = sgroupfetch4( c1, QtyOnHand, Len(QtyOnHand), TotCost, Len(TotCost), "", 0, "", 0) MessStr = "Qty On Hand "
+ Str$(QtyOnHand) + "Total Cost "+ Str$(TotCost) Call MessBox( MessStr, MB_OK, "Message")
See Also
SFetch Functions, Sql Statement
Microsoft Dynamics SL API Function Calls 165
SInsert Statements
Insert one record into each specified table within an existing database view.
Syntax
Call SInsert1( Cursor, TablesInsertingInto, bTable1, bTable1Length)
Call SInsert4( Cursor, TablesInsertingInto, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length,
bTable4, bTable4Length)
Call SInsert8( Cursor, TablesInsertingInto, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length,
bTable4, bTable4Length, bTable5, bTable5Length, bTable6, bTable6Length, bTable7, bTable7Length, bTable8,
bTable8Length)
Remarks
New records can be programmatically inserted directly into an existing database table via the use of the SInsert1,
SInsert4 and SInsert8 statements. In order to insert information into the database, the server must first know what tables
are being referenced by a particular cursor. Consequently the cursor must first be initialized with either an SQL
statement or stored procedure via the use of the Sql statement or the SqlFetch1, SqlFetch4 or SqlFetch8
functions. Once the database view has been established these functions will insert one new record into each table
referenced in the TablesInsertingInto argument using data from corresponding table structure arguments.
SInsert1 is designed for SQL statements referencing a single table. In this case the
TablesInsertingInto is always the name of the single table actually referenced. For more advanced SQL statements
having one or more table joins either SInsert4 or SInsert8 can be used. The referencing of more than one table does not
automatically force the insertion of a record into every table in the view any time SInsert4 or SInsert8 is used on the
corresponding cursor. A single record will only be inserted into each table explicitly specified in the
TablesInsertingInto argument so long as each table name so specified is also referenced in the SQL statement which was
used to initialize the current view. Thus, for example, if TableA and TableB are the only two tables referenced in the SQL
statement used to initialize the current view then a value of TableXYZ would be invalid for the TablesInsertingInto argument.
The SInsert1 function uses the following arguments ( SInsert4 and SInsert8 respectively have four and eight table
structures and corresponding lengths. PNULL should be passed for unused table structure parameters as well as a
corresponding length of zero such as PNULL, 0).
TablesInsertingInto String Name of each table, in the specified cursors view, into which a new record is to be
inserted. Multiple table names should be separated by commas.
bTable1 User-defined Table structure corresponding to the primary table in the SQL statement. Data in this
datatype structure will be inserted into its corresponding database table if the name of the said
database table is explicitly specified in the TablesInsertingInto argument.
bTable1Length Integer Size of first table structure. For example, LenB( bTable1). Note: It is critical to use LenB() instead
of Len() for all non-null table length parameters.
166 Customization Manager Reference Visual Basic for Applications
Example
The example shows an OnUpdate event of a Microsoft Dynamics SL screen.
If Level = 0 Then
bXCustAddlInfo,Len(bXCustAddlInfo)) Else
Insert new entry into Customer and ARHist tables Call Sinsert4( c1, "*.*", bCustomer, Len(bCustomer),
See Also
Sql Statement, SqlFetch Functions
Microsoft Dynamics SL API Function Calls 167
SParm Function
Convert a string into an SQL parameter string.
Syntax
SQLParmStr = SParm( StrToConvert)
Remarks
The SParm function uses the following arguments:
Example
These examples assume the following SQL statement was used to create a stored procedure called
Employee_EmpId.
Select * from Employee where EmpId LIKE @parm1 order by EmpId
This code snippet illustrates how to use the Employee_EmpId stored procedure to fetch the employee record for
employee 000581.
SqlStr = "Employee_EmpId" + SParm("000581")
Employee_Fetch = SqlFetch1(CSR_Employee, SqlStr, bEmployee, LenB(bEmployee))
This code snippet illustrates how to use the Employee_EmpId stored procedure to fetch all employee records by
using a wildcard value for the EmpId parameter.
SqlStr = "Employee_EmpId" + SParm(SQLWILDSTRING) Employee_Fetch = SqlFetch1(CSR_Employee, SqlStr,
bEmployee, LenB(bEmployee))
While ( Employee_Fetch = 0)
Employee_Fetch = SFetch1( CSR_Employee, bEmployee, LenB(bEmployee)) Wend
This code snippet illustrates how to use the Employee_EmpId stored procedure to fetch all employee records beginning
and ending with zero by using a combination of string literals and single character wildcard values for the EmpId
parameter.
SQLParmStr = "0" + SQLWILDCHAR + SQLWILDCHAR + SQLWILDCHAR
+ SQLWILDCHAR + "0"
SqlStr = "Employee_EmpId" + SParm(SQLParmStr) Employee_Fetch = SqlFetch1(CSR_Employee, SqlStr, bEmployee, LenB(bEmployee)) While (
Employee_Fetch = 0)
See Also
DParm Function, FParm Function, IParm Function
168 Customization Manager Reference Visual Basic for Applications
SQL Statement
Initialize a new database view.
Syntax
Call Sql( Cursor, SqlStr)
Remarks
Takes the specified SQL text, compiles it, and then executes it. If fetch operations are required then one of the SFetch functions
must be called. If the SQL statement is performing an Update Set, Delete From or Insert Into operation, no subsequent
fetch operations are required. If the SQL statement references one or more parameters, the SqlSubst and SqlExec functions
must also be called. The Sql statement uses the following arguments:
SqlStr String SQL statement or stored procedure to be used in initializing a new database view. If a
stored procedure is used then all parameters must be sequentially appended in order of
occurrence within the original Create Procedure statement using calls to SqlSubst.
Example
Dim SqlStr As String
AP batches
SqlStrg = "Select * from Batch Where Module = 'AP' and Status = 'P'
Order By BatNbr" Call Sql( CSR_Batch,
SqlStrg)
See Also
SFetch Functions, SqlExec Statement, SqlSubst Statement
Microsoft Dynamics SL API Function Calls 169
SqlCursor Statement
Allocate a new database cursor.
Syntax
Call SqlCursor( Cursor, Flags)
Remarks
All read/write communication between an application and the database must occur through a database cursor. A cursor
is basically a database resource used to track low level information required to implement SQL database read/write
operations. For example, a cursor tracks the SQL statement used to initialize the current view, what individual fields were
selected, the current record within the view as well as other more detailed information. Each level within a screen must
have a corresponding cursor allocated within the Form_Load event of Form1 to facilitate database read/write activity at
that level. Additionally, many of the SQL API calls within Microsoft SL SDK, such as Sql, SFetch1, SqlFetch1 and SUpdate1
Flags Integer One or more special flags notating what and/or how the cursor will be used. At a minimum
the Flags parameter must contain one of the LEVEL0 through LEVEL9 or NOLEVEL
symbolic constants defined in the VBTools_VBA module. Cursors not explicitly associated
with a particular level number should be allocated using the NOLEVEL flag.
The following symbolic constants can optionally be passed as Flags ( by adding them to the required LEVEL0 through
LEVEL9 or NOLEVEL symbolic constants):
SqlList Read/write operations performed on the cursor will automatically be buffered to improve performance. If an
application updates even one record on a buffered cursor, it must update all records read with that cursor within the
same database transaction. Failure to comply with this requirement will result in a sparse update error.
SqlSystemDb All database operations will be directed to the system database as opposed to the application
database.
Example
'Example declares a dynamic cursor in Form1_Load 'because it will be used elsewhere in the application
'NoLevel indicates no updating on this cursor, 'only lookups will be performed Call SqlCursor( c1,
NoLevel)
'NoLevel + SQLList indicates a buffered cursor Call SqlCursor( c2, NoLevel + SqlList) 'Example
'that a previous SqlCursor call was not made for c3: Dim SqlStmt$
serr1 = SgroupFetch1(c3, CountResult, Len(CountResult)) Call MessBox("Count is: " + Str$(CountResult), MB_OK,
"Message")
See Also
SFetch Functions, SInsert Statements, Sql Statement, SqlFetch Functions, SqlFree Statement, SUpdate Statements
Microsoft Dynamics SL API Function Calls 171
SqlCursorEx
Allocate a new database cursor.
Syntax
Call SqlCursorEx( Cursor, Flags, CursorName, ReferencedTableNames, UpdateTableNames)
Remarks
All read/write communication between an application and the database must occur through a database cursor. A cursor
is basically a database resource used to track low level information required to implement SQL database read/write
operations. For example, a cursor tracks the SQL statement used to initialize the current view, what individual fields were
selected, the current record within the view as well as other more detailed information. Each level within a screen must
have a corresponding cursor allocated within the Form_Load event of Form1 to facilitate database read/write activity at
that level. Additionally, many of the SQL API calls within Microsoft SL SDK, such as Sql, SFetch1, SqlFetch1 and SUpdate1
require a database cursor as one of their arguments. If the cursor handle passed to one of these SQL API calls has not
been previously allocated then it will automatically be allocated during the call. However it is important to be aware of the
fact that all cursors not explicitly allocated, via an SqlCursorEx call, are automatically allocated as read-only cursors. Each
application can allocate a maximum of 36 cursors. Cursors no longer needed by the application can optionally be freed via
the use of the SqlFree statement. All cursors are automatically released by the system when the application terminates
execution (when
Flags Integer One or more optimization flags notating what and/or how the cursor will be
used. At a minimum the Flags parameter must contain one of the LEVEL0
through LEVEL9 or NOLEVEL symbolic constants defined in the
VBTools_VBA module. Cursors not explicitly associated with a particular
level number should be allocated using the NOLEVEL flag.
CursorName String Alias name associated with the cursor. This value is used solely to
enhance the readability of diagnostic messages.
ReferencedTableName s String Comma-delimited list of table names that will be referenced by the cursor.
This list should be thought of as being applicable so long as the cursor
remains allocated.
UpdateTableNames String Comma-delimited list of all tables which may be updated by the cursor. The
principle usage of this list is to facilitate performance optimizations related to
tables in the cursors view that will never be updated. If no table names are
specified then by default it will be assumed that all of the referenced tables
will be updated at some point. Any table name appearing in
UpdateTableNames must also be specified in ReferencedTableNames. This
list of table names should not be confused with the table names passed to
any of the SInsert, SUpdate or SDelete statements. The names passed to
those statements identify the actual tables updated in a particular database
operation, which may be a subset of the UpdateTableNames argument.
172 Customization Manager Reference Visual Basic for Applications
Note: The following optimization flags are implemented as symbolic constants in the VBTools_VBA module. They can
optionally be passed via the Flags argument by adding them to the required LEVEL0 through LEVEL9 or NOLEVEL
symbolic constant:
SqlFastReadOnly Similar to SqlReadOnly, the cursor will be used exclusively for read operations. On the SQL
Server platform, all database operations occurring on an SqlFastReadOnly cursor will be serviced directly from SQL
Servers faster low-level API. Please refer to the note below for more information regarding the practical implications
of utilizing SQL Servers low level API. Cursors with this flag should not be used to access tables which have
received insert, update or delete operations from a different cursor in the same database transaction.
SqlList Read/write operations performed on the cursor will automatically be buffered to improve performance. If an
application updates even one record on a buffered cursor, it must update all records read with that cursor within the
same database transaction. Failure to comply with this requirement will result in a sparse update error. In the SQL
Server environment, all database operations are buffered where possible, regardless of whether the SqlList flag has
been specified. Refer to the SqlNoList flag for more information.
SqlLock Every composite record retrieved with this type of cursor will be locked. This flag effectively avoids the
overhead of explicitly locking every record that is fetched from the database within a transaction. SqlLock is primarily
designed for usage in process-like scenarios where it is known in advance that every record accessed by the cursor
needs to be updated. If the application will ever be waiting for user-input while the cursor still has a current record then
the cursor should probably not be allocated with the SqlLock flag. This is due to the simple fact that the current record
would be locked while waiting for the user to respond, thus potentially causing contention across the system. Records
retrieved on SqlLock cursors will remain locked until the next record is retrieved. For this reason, the application
should always continue to fetch records until a NOTFOUND is returned, thereby unlocking the last record which was
actually retrieved. It is strongly recommended that applications only implement the usage of SqlLock to facilitate
optimum performance as opposed to using it to implement their own multi-user contention management scheme (that
is, process XYZ must be running because such and such a record is locked). This flag is only supported on the SQL
Server platform.
SqlNoList This flag forces the buffering of read/write operations to be suppressed. In the SQL Server environment
all database operations are buffered by default, where possible, regardless of whether or not the SqlList flag has been
specified. Consequently on the SQL Server platform, buffering must be explicitly suppressed if for some reason the
application does not want a particular cursor to be buffered. In some cases this default buffering is automatically
suppressed due to low level restrictions.
SqlNoSelect This flag indicates that the cursor will be used with any SQL statement except Select statements.
The most common usage of this type of cursor will be to process Update and Delete SQL statements. On the SQL
Server platform, all database operations occurring on a SqlNoSelect cursor will be serviced directly from SQL
Servers faster low- level API. Please refer to the note below for more information regarding the practical implications
of utilizing SQL Servers low level API.
SqlReadOnly The cursor will be used exclusively for read operations. The cursor will not be used for record
inserts, updates or deletions.
SqlSingleRow This flag is to be used with cursors which will never process more than one composite record after
each Select statement. This flag is primarily designed to facilitate optimization on the SQL Server platform. On the
SQL Server platform, all database operations occurring on an SqlSingleRow cursor will be serviced directly from SQL
Servers faster low-level API. Please refer to the note below for more information regarding the practical implications
of utilizing SQL Servers low level API. SFetch calls on cursors of this type should not be separated from the
associated Sql call by any other database
Microsoft Dynamics SL API Function Calls 173
operations. The simplest method to satisfy this requirement is via the usage of the
SqlFetch function.
SqlSystemDb All database operations will be directed to the system database as opposed to the application
database.
Note: Regarding the optimization flags which invoke usage of SQL Servers low-level API (SqlFastReadOnly, SqlNoSelect
and SqlSingleRow): On the SQL Server platform, all database operations occurring on a cursor optimized with one of
these flags will bypass SQL Servers standard cursor API. Instead, database operations will be serviced directly from
SQL Servers low level API. The advantage here is that the low level API is faster. However, when using the low level API
the cursor can encounter contention with other cursors in the same application (which is not the case when all operations
are serviced by SQL Servers cursor API). SQL statements processed via this type of cursor must include all of the fields
for every table referenced in the statement. For example, partial record Select statements are not supported on this type
of cursor.
174 Customization Manager Reference Visual Basic for Applications
SqlErr Function
Obtain the return value for the SQL operation last performed.
Syntax
RetVal = SqlErr()
Remarks
This function can be used after any SQL call that is declared as a statement (as opposed to a function), in order to obtain
the return value. For example, the call SInsert1 is declared as a subroutine and does not return a value to the application.
In most cases, the application does not need to check the return from this call, since by default SWIM traps all return codes
except 0 and the NOTFOUND symbolic constant. However in special cases where the SqlErrException
statement is used to give the application more control over error handling, the application will need to obtain the return
code and this function is used for that purpose. The SqlErr function returns one of the following integer global constants
declared in the VBTools_VBA module:
Example
This example illustrates how to insert a uniquely numbered Batch record into the database. The example assumes
that a database transaction is already active when the illustrated procedure is called. SqlErrException and SqlErr are
used to detect duplicate batch number error without causing Swim to abort the transaction. The sample procedure
receives two parameters:
BatchStruct A Batch record which is to be saved to the database, having all relevant fields ALREADY
initialized EXCEPT the batch number itself.
AutoNbr_SqlStr The name of an auto number stored procedure which will fetch AutoBat and LastBatNbr
fields (in that order) from one of the setup records.
Sub BATCH_AUTONBR_INSERT (BatchStruct As Batch, ByVal AutoNbr_SqlStr As String)
NOLEVEL)
AutoNbrFetch = SqlFetch1(CSR_AutoNbr,
AutoNbr_SqlStr, AutoNbr,
LenB(AutoNbr))
used).
Call incrstrg(AutoNbr.LastNbrUsed, 6, 1) BatchStruct.BatNbr =
number
Call SInsert1(CSR_Batch_AutoNbr_Insert,
"Batch", BatchStruct, LenB(BatchStruct)) Loop While (SqlErr() = DUPLICATE) 'Write changes
End Sub
See Also
SqlErrException Statement
176 Customization Manager Reference Visual Basic for Applications
SqlErrException Statement
Toggle automatic error handling logic for one or more database error codes.
Syntax
Call SqlErrException ( ToggleFlag, ErrorToExcept)
Remarks
By default, all error codes except 0 and NOTFOUND are trapped within SWIM and are not returned to the application.
To alter this behavior an application can use the SqlErrException
function to tell SWIM not to trap certain errors and instead return them to the application. This statement is used in
conjunction with the SqlErr function.
Note that the application is responsible for toggling the exception back off once it is no longer needed. The SqlErrException
statement uses the following arguments:
ErrorToExcept Integer Error code to be returned to the application rather than handled automatically by the
system. If only duplicate record errors should be excepted from automatic error handling
logic then the DUPLICATE symbolic constant defined in the VBTools_VBA module should
be passed. The RETURN_ALL_ERRVALS symbolic constant defined in the VBTools_VBA
module should be passed if all errors are to be returned to the application.
Example
Dim DupFlag% DupFlag =
DUPLICATE
'Tell Microsoft Dynamics SL to return DUPLICATE status messages Call SqlErrException( EXCEPTION_ON, DUPLICATE)
'Loop until a non duplicate number is assigned Do Until DupFlag <> DUPLICATE
See Also
SqlErr Function
Microsoft Dynamics SL API Function Calls 177
SqlExec Statement
Execute an inline SQL statement.
Syntax
Call SqlExec( Cursor)
Remarks
Execute a dynamic SQL statement on a cursor previously initialized with calls to the Sql and
SqlSubst statements (in that order). The SqlExec statement uses the
following arguments:
Example
Dim VendorCount&, SqlStmt$
SqlStmt = "Select Count(*) from Vendor Where VendId Like @parm1" Call Sql(c1, SqlStmt)
"Message")
See Also
SQL Statement, SqlSubst Statement
178 Customization Manager Reference Visual Basic for Applications
SqlFetch Functions
Used to initialize a new database view and immediately retrieve a composite record.
Syntax
RetVal = SqlFetch1( Cursor, SqlStr, bTable1, bTable1Length) RetVal = SqlFetch4( Cursor, SqlStr, bTable1,
bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length) RetVal = SqlFetch8(
Cursor, SqlStr, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length, bTable4,
bTable4Length, bTable5, bTable5Length, bTable6, bTable6Length, bTable7, bTable7Length, bTable8,
bTable8Length)
Remarks
In order to fetch information from the database, a database view must first be initialized specifying what tables, fields and
restriction criteria are to be utilized. Secondly an actual request for data from an existing view must be sent to the server.
Each of the SqlFetch1, SqlFetch4 and SqlFetch8 functions effectively perform both of these operations in a single call
which would otherwise require a combination of two calls ( Sql and SqlFetch1). In looping situations where a program needs
to sequentially read through multiple records in a view, these functions are convenient for initializing the view and
immediately fetching the first record. However they should not be used to fetch subsequent records since the view is being
re-established each time SqlFetch1, SqlFetch4 or SqlFetch8 is called and therefore they will always only fetch the first
record in the view. In these cases, SFetch1, SFetch4 or SFetch8 can be used to fetch subsequent records.
SqlFetch1 is designed for SQL statements returning data from a single table. For more advanced SQL statements having
one or more table joins either SqlFetch4 or SqlFetch8 can be used. The SqlFetch1 function uses the following arguments ( SqlFetch4
and SqlFetch8 respectively have four and eight table structures and corresponding lengths. PNULL should be passed for
unused table structure parameters as well as a corresponding length of zero such as PNULL, 0).
SqlStr String SQL statement or stored procedure to be used in initializing a new database view. If a
stored procedure is used then all parameters must be sequentially appended in order of
occurrence within the original Create Procedure statement. These parameter values must
also be properly converted to SQL parameters via usage of the SParm, IParm, FParm and
DParm functions, whichever is appropriate for the datatype of each individual parameter.
bTable1 User-defined Table structure corresponding to the primary table in the SQL statement.
datatype
bTable1Length Integer Size of first table structure. For example, LenB( bTable1). Note: It is critical to use LenB() instead
of Len() for all of the non-null table length parameters.
Microsoft Dynamics SL API Function Calls 179
SGroupFetch1, SGroupFetch4 or SGroupFetch8 must be used if the SQL statement used to initialize the cursor
contains one or more of the following components:
DISTINCT keyword
GROUP BY clause
HAVING clause
Subqueries
Example 1
This example from a CustId Chk event that fetches new table information.
SUB ccustid_Chk(chkstrg$, retval%)
bXCustAddlInfo, Len(bXCustAddlInfo))
Example 2
'Select Unreleased APDocs and Join Vendor Table Dim SqlStmt$
"", 0, "", 0)
See Also
DParm Function, FParm Function, IParm Function, SGroupFetch Functions, SParm Function, Sql Statement, SqlFetch
Functions
180 Customization Manager Reference Visual Basic for Applications
SqlFree Statement
Free a database cursor no longer needed by the application.
Syntax
Call SqlFree( Cursor)
Remarks
The SqlFree statement is used to deallocate cursors previously allocated with the SqlCursor
statement. The usage is this statement is entirely optional. It is normally used when a cursor is no longer needed by an
application whose total number of cursors is very close to the maximum limit. All cursors are automatically released by the
system when the application terminates execution (when ScreenExit is called). The SqlFree statement uses the following
arguments:
Example
This example uses SqlFree in a general subroutine.
Get APSetup Information set global variable NextRefNbr Sub GetSetupInfo()
Call SqlCursor(c1)
Call SqlFetch1(c1, "APSetup_All", bAPSetup, Len(bAPSetup)) NextRefNbr = bAPSetup.LastRefNbr Call SqlFree( c1)
End Sub
See Also
SqlCursor Statement
Microsoft Dynamics SL API Function Calls 181
SqlSubst Statement
Specify a data value for a substitution parameter in an inline SQL statement previously executed via the Sql function.
Syntax
Call SqlSubst( Cursor, ParmName, ParmValue)
Remarks SqlSubst allows you to specify values for one or more substitution variables in an inline SQL statement that is
executed via the Sql statement. It is not to be used for a stored procedure. This statement must be called after the Sql statement
and before the SqlExec statement. It can be called any number of times before SqlExec is called, depending on how may
parameter values there are to substitute into the SQL statement. The SqlSubst statement uses the following arguments:
ParmName String Name of the SQL statement parameter (not including the @ character)
Example
Dim VendorCount&, SqlStmt$
SqlStmt = "Select Count(*) from Vendor Where VendId Like @parm1" Call Sql(c1, SqlStmt) Call SqlSubst( c1, "parm1",
serr1 = sgroupfetch1(c1, VendorCount, Len(VendorCount)) Call MessBox ( "Count is " + Str$(VendorCount), MB_OK,
"Message")
See Also
SQL Statement, SqlExec Statement
182 Customization Manager Reference Visual Basic for Applications
StrToDate Statement
Convert a date value from a string in MMDDYYYY format into an SQL date format.
Syntax
Call StrToDate( DateStringToConvert, SQLDate)
The StrToDate statement uses the following arguments:
Example
Dim NewDate As Sdate Call StrToDate(" 10311994", NewDate)
See Also
DateToIntlStr Function, DateToStr Function, DateToStrSep Function, IntlStrToDate Statement
StrToTime Statement
Convert a time value from a string in HHMMSShh format into an SQL time format.
Syntax
Call StrToTime( TimeStringToConvert, SQLTime)
The StrToTime statement uses the following arguments:
Example
Dim TimeVal As Stime Dim TimeStr As String TimeStr =
See Also
TimeToStr Function
Microsoft Dynamics SL API Function Calls 183
SUpdate Statements
Update one record of each specified table within an existing database view.
Syntax
Call SUpdate1( Cursor, TablesUpdating, bTable1, bTable1Length)
Call SUpdate4( Cursor, TablesUpdating, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length,
bTable4, bTable4Length)
Call SUpdate8( Cursor, TablesUpdating, bTable1, bTable1Length, bTable2, bTable2Length, bTable3, bTable3Length,
bTable4, bTable4Length, bTable5, bTable5Length, bTable6, bTable6Length, bTable7, bTable7Length, bTable8,
bTable8Length)
Remarks
Existing records can be programmatically updated directly via the use of the SUpdate1, SUpdate4 and SUpdate8 statements.
However, before a record can be updated it must first be fetched using one of the SFetch1, SFetch4 and SFetch8 or SqlFetch1,
SqlFetch4 and
SqlFetch8 functions. The fetch operation which precedes the update must be made using the same database view/cursor
on which the update will occur. For example, if the fetch occurs on Cursor A then the update must also occur on Cursor A
as opposed to some unrelated Cursor XYZ. Nevertheless, once the database view has been established these functions
will update the current record in the view for each table referenced in the TablesUpdating argument using data from
corresponding table structure arguments.
SUpdate1 is designed for SQL statements referencing a single table. In this case the
TablesUpdating is always the name of the single table actually referenced. For more advanced SQL statements having one
or more table joins either SUpdate4 or SUpdate8 can be used. The referencing of more than one table does not
automatically force the current record of every table within the view to be updated any time SUpdate4 or SUpdate8 is used
on the corresponding cursor. The current record of a particular table in the view will only be updated if its corresponding
table name is explicitly specified in the TablesUpdating argument so long as each table name so specified is also
referenced in the SQL statement which was used to initialize the current view. Thus, for example, if TableA and TableB
are the only two tables referenced in the SQL statement used to initialize the current view then a value of TableXYZ would
be invalid for the TablesUpdating argument. The SUpdate1 function uses the following arguments ( SUpdate4 and SUpdate8
respectively have four and eight table structures and corresponding lengths. PNULL should be passed for unused table
structure parameters as well as a corresponding length of zero such as PNULL, 0).
TablesUpdating String Name of each table, in the specified cursors view, whose current record is to be
updated. Multiple table names should be separated by commas.
bTable1 User-defined Table structure corresponding to the primary table in the SQL statement. Data
datatype from this structure will be used to overwrite existing data in the corresponding
current record if the name of the said database table is explicitly specified in the
TablesUpdating argument.
bTable1Length Integer Size of first table structure. For example, LenB( bTable1). Note: It is critical to use LenB()
instead of Len() for all non-null table length parameters.
Note: Database updates occurring on cursors allocated by SqlCursorEx using the SqlList flag (buffered cursors) have two
unique requirements. First, the application must update all records
184 Customization Manager Reference Visual Basic for Applications
it reads, using a buffered cursor, if it updates even one record. Failure to comply with this requirement will result in a
sparse update error. Secondly, the application should not modify the view on the cursor after updates have occurred
until after the transaction has ended. For example if the application is reading and updating Table A records on buffered
Cursor A then Cursor A should not be used for any other purpose until after the database transaction has ended. If no
updates are made using Cursor A then this requirement does not apply.
Example
This simple example updates all GLTran records in General Ledger Batch 000001 as being released. Within Microsoft
Dynamics SL, the release of GLTran records actually entails additional application logic which is not directly relevant to
the illustration of the SUpdate4 statement and therefore it has been removed from this example.
This example assumes the GLTran_Module_BatNbr_LineNbr stored procedure was originally created with the
following SQL statement:
Select * from GLTran
@parm2
LineNbr
Since the SQL statement above only retrieves data from a single table (for example, the GLTran table) SUpdate1
would be adequate. However in this example, SUpdate4 is actually used to illustrate how to pass "", 0 for unused
table structure arguments.
'Allocate a database cursor. A buffered cursor (i.e., SqlList) can be 'used to speed up performance since ALL GLTran records read within
the 'database transaction will also be updated.
Call SqlCursor( CSR_GLTran, NOLEVEL + SqlList) 'Begin a database transaction since all updates to the database must
occur
'within a transaction.
Call TranBeg(True)
'Initialize cursor with a SQL stored procedure and immediately fetch 'first record
While (GLTranFetch = 0)
Wend
See Also
SFetch Functions, SqlCursor Statement, SqlFetch Functions
186 Customization Manager Reference Visual Basic for Applications
TestLevelChg Function
Return the current update status flag for a specific level.
Syntax
Status = TestLevelChg( LevelNbr)
Remarks
Each update level, as defined by the Levels property of the SAFUpdate control, has a corresponding level status flag that is
automatically maintained by the system. The purpose of the level status flag is to facilitate the optimization of database
updates performed in response to Microsoft Dynamics SL toolbar buttons. In general, these flags allow the system to only
perform database updates for update levels which have in fact changed. If no information has changed then no information
needs to be saved.
As previously mentioned, these update flags are automatically maintained by the system. When an existing record is
loaded the flag is set to NOTCHANGED. If any non-key field is subsequently modified then the level status flag for the
corresponding level is set to UPDATED. When a new record is being entered, the level status flag is set to INSERTED.
The TestLevelChg function allows the application to access the current value of this flag for a specific level. The current
level status flag can be overridden by the application using the
Example
The Payroll modules Earnings Type Maintenance ( 02.270.00) window contains a button to automatically populate the grid
with all Deductions. This amounts to inserting records into the grid (that is, into its underlying memory array) under
program control. Since the data is not entered via the user interface by the user, the system needs to be notified that
information at the grid level (LEVEL1 in this case) has been programmatically updated and therefore needs to be saved.
However, such notification only needs to occur if the system is not already aware that data has changed.
'If any records were inserted into the memory array then we need to make 'sure that the level status for the detail level is something other than
See Also
SetLevelChg Statement
Microsoft Dynamics SL API Function Calls 187
TimeToStr Function
Convert a time value from SQL time format into a string in HHMMSShh format.
Syntax
TimeString = TimeToStr( TimeToConvert)
Remarks
The TimeToStr function uses the following arguments:
Example
'If any records were inserted into the memory array then we need to make 'sure that the level status for the detail level is something other than
See Also
StrToTime Statement
188 Customization Manager Reference Visual Basic for Applications
TranAbort Statement
Abort the current database transaction.
Syntax
Call TranAbort
Remarks
The TranAbort statement allows the application to abort a database transaction which was initiated using the TranBeg statement.
Calling TranAbort directly is not, however, the recommended method to abort transactions. If the transaction to be
aborted is an update operation for an application screen then the recommended method is for the application to set
RetVal in the OnUpdate event of the
SAFUpdate control to either an error message number or the ErrNoMess symbolic constant defined in the
VBTools_VBA module. This will also have the effect of aborting the current database transaction.
Example
Call TranBeg(True)
. . . .
'Perform Processing
. . . . .
'Determine any error condition that would cause the transaction to abort If ErrorCondition Then
Call TranAbort
End If
Supdate... OR
Sdelete...
See Also
TranBeg Statement, TranEnd Statement, OnUpdate Event
Microsoft Dynamics SL API Function Calls 189
TranBeg Statement
Begin a database transaction.
Syntax
Call TranBeg( IsAbortable)
Remarks
All updates to the database must occur within a database transaction. All updates to the database will not actually be
committed to the database until the transaction is ended via the
TranEnd statement.
If any errors occur during the database transaction, the system will automatically abort (roll back) all updates occurring
during the transaction as opposed to committing them to the database. If the transaction is an update operation for an
application screen then it will be aborted when the application to sets RetVal in the OnUpdate event of the SAFUpdate control
to either an error message number or the ErrNoMess symbolic constant defined in the VBTools_VBA module. The TranBeg
statement uses the following argument:
Example
Call TranBeg( True) 'Perform
Processing
'Determine any error condition that would cause the transaction to abort If ErrorCondition Then
Supdate... OR
Sdelete
See Also
TranEnd Statement, TranStatus Function, OnUpdate Event
190 Customization Manager Reference Visual Basic for Applications
TranEnd Statement
End the current database transaction and commit all updates to the database.
Syntax
Call TranEnd
Remarks
If any errors occurred during the database transaction, the system will automatically abort (roll back) all updates which
occurred during the transaction as opposed to committing them to the database. If the transaction is an update operation
for an application screen then it will be aborted when the application to sets RetVal in the OnUpdate event of the SAFUpdate
control to either an error message number or the ErrNoMess symbolic constant defined in the VBTools_VBA module.
Example
Call TranBeg(True) 'Perform
Processing
'Determine any error condition that would cause the transaction to abort If ErrorCondition Then
Supdate... OR
Sdelete...
See Also
TranBeg Statement, TranStatus Function, OnUpdate Event
Microsoft Dynamics SL API Function Calls 191
TranStatus Function
Returns the status of the current or last database transaction.
Syntax
IntegerErrVal = TranStatus()
Remarks
If a database transaction is currently not open then the status of the last performed database transaction is returned.
Example
Call TranBeg(True) 'Perform
Processing
'Determine any error condition that would cause the transaction to abort If ErrorCondition Then
Supdate... OR
Sdelete...
See Also
TranBeg Statement, TranEnd Statement, OnUpdate Event
192 Customization Manager Reference Visual Basic for Applications
VBA_MExtend Function
Extend the grid of an application so that another tables structure can be added to the grid.
Syntax
RetVal = VBA_MExtend( MemHandle, bTable1, bTable1Length)
Remarks
Although this function is provided to extend the number of tables that are accessed by the grid control, the VBA application
is responsible for all database I/O to the new table. This includes using memory array functions to cycle through the grid at
save time to determine if the contents of the structure of the underlying table has changed and perform the appropriate
action. The VBA_MExtend function uses the following arguments:
bTable1 User-defined Supplementary table structure to be added to the existing memory array.
datatype
Example
The following example extends the grid for the General Ledger Chart of Accounts Maintenance
(01.260.00) screen. It adds the definition of a new table, XAccount, to the account grid.
Global GridHandle As Integer 'Calls in Form1_Load
event:
Call VBA_SetAddr("bXAccount", bXAccount, nXAccount, LenB(bXAccount)) Call SQLCursor(c1, NOLEVEL) 'Calls in Form1_Display
See Also
GetGridHandle Function, VBA_SetAddr Statement
Microsoft Dynamics SL API Function Calls 193
VBA_MOpen Functions
Open a new memory array and return a corresponding unique memory array number.
Syntax
MemHandle = VBA_MOpen( DelRetToSystem, bTable1, bTable1Length, bTable2, bTable2Length, bTable3,
bTable3Length, bTable4, bTable4Length) MemHandle = VBA_MOpen8( DelRetToSystem, bTable1, bTable1Length,
bTable2, bTable2Length, bTable3, bTable3Length, bTable4, bTable4Length, bTable5, bTable5Length, bTable6,
bTable6Length, bTable7, bTable7Length, bTable8, bTable8Length)
Remarks
A memory array must be opened before insert, update, delete or memory array navigation operations can be
performed on it. The memory array handle returned by VBA_MOpen and
VBA_MOpen8 are used when performing these types of operations on memory arrays.
VBA_MOpen allocates memory for up to four table structures whereas VMA_MOpen8 can handle up to eight
different table structures for each memory array record.
VBA_MOpen is only used to open memory arrays which are not associated with an SAFGrid
control. Memory arrays which correspond to grids are opened automatically. The VBA_MOpen function uses the
following arguments ( VBA_MOpen8 has eight table structures and corresponding lengths. PNULL should be
passed for unused table structure parameters as well as a corresponding length of zero such as PNULL, 0).
bTable2 User-defined Second table structure of memory array. PNULL if the memory array only contains one
datatype table structure.
bTable2Length Integer Size of second table structure. Zero if the memory array only contains one table structure.
bTable3 User-defined Third table structure of memory array. PNULL if the memory array contains less than
datatype three table structures.
bTable3Length Integer Size of third table structure. Zero if the memory array contains less than three table
structures.
bTable4 User-defined Fourth table structure of memory array. PNULL if the memory array contains less than
datatype four table structures.
bTable4Length Integer Size of fourth table structure. Zero if the memory array contains less than four table
structures.
The table structures passed to VBA_MOpen8 do not have to be actual database tables. They can be either a simple data
item, such as a double, or any user-defined data type created with the Visual Basic Type statement.
Example
This example illustrates how to open a memory array and load the entire chart of accounts into the newly-created array.
'Open memory array to hold Chart of Accounts Mem_Account = VBA_MOpen( TRUE, bAccount, Len(bAccount), PNULL, 0, PNULL,
0,
PNULL, 0)
'Allocate cursor
'Initialize cursor with a SQL stored procedure and immediately fetch 'first record
'Read through all subsequent Account records, inserting each one 'into the memory array.
While( Account_Fetch = 0)
Wend
See Also
MClear Statement, MClose Statement, MDelete Function, MDisplay Statement, MFirst Function, MInsert Statement,
MKey Statement, MKeyFind Function, MLast Function, MNext Function, MPrev Function, MUpdate Statement
Microsoft Dynamics SL API Function Calls 195
VBA_SetAddr Statement
Associate a table name together with a Visual Basic variable and an optional screen level number.
Syntax
Call VBA_SetAddr( TableNameStr, bTableName, nTableName, bTableNameLength)
Remarks
The VBA_SetAddr statement facilitates proper runtime binding between a Visual Basic data variable and relevant data
entry controls, including controls created using the Customization Manager.
Although SWIM has access to extensive information about any particular data entry control, one vital piece of information
cannot be determined merely by looking at the control itself. In particular, SWIM needs to know where the data for the
control is stored in memory. Since the data is actually stored in an underlying Visual Basic variable, SWIM has no means of
directly determining where that Visual Basic variable is stored in memory. The VBA_SetAddr statement is used by the
application to resolve this problem. To facilitate the explanation of the linkage between the VBA_SetAddr statement and
corresponding data entry controls, consider the following user-defined datatype and a corresponding VBA_SetAddr call for
the Account database table:
As String * 10
Active As Integer
ConsolAcct As String * 10
CuryId As String * 4
Descr As String * 30
NoteID As Long
RatioGrp As String * 2
SummPost As String * 1
Type As String * 2
User1 As String * 30
User2 As String * 30
User3 As Double
User4 As Double
End Type
Global bVBVarAccount As Account, nVBVarAccount As Account Call VBA_SetAddr( " bAccount", bVBVarAccount,
nVBVarAccount,
LenB(bVBVarAccount))
The VBA_SetAddr call itself associates the value of the TableNameStr argument together with the memory location of the
first byte of the Visual Basic variable passed via the bTableName
argument. If the relevant table is a database table, SWIM can access detailed information relating to each individual field
contained therein using the SQL data dictionary. For example, SWIM can determine the name, data type, maximum size,
and relative placement (byte offset) of each individual field within the table. After the VBA_SetAddr call in the above
example, SWIM would know that the first byte of bVBVarAccount is at a particular location in memory, hereafter referred to
as location M, and furthermore that the first byte of bVBVarAccount.Acct is offset zero bytes from location M as well as the
fact that Acct is ten bytes long. Similarly, it would also know that the first byte of bVBVarAccount.Active is offset ten bytes
from location
M, and is two bytes long since it is an integer. Since the value of bAccount is passed as the
196 Customization Manager Reference Visual Basic for Applications
TableNameStr argument it is the string literal associated with memory location M. Any time SWIM encounters
bAccount.<SomeFieldName> in a FieldName property it will have all of this detailed information readily available so it
can access the corresponding data at the appropriate memory location. The same concept applies when SWIM
encounters bAccount.<SomeFieldName> in any of the DBNav, Default, PV or Trigger properties. As previously
mentioned, the detailed information acquired by SWIM as a result of the
VBA_SetAddr call can be directly linked to the FieldName property of data entry controls. The FieldName property
contains a Struct.FieldName value along with other more detailed information such as field offset value, declare type and
length. Once they have been fully initialized, these values facilitate the linkage between the control and the associated
memory location where the data value of the control is stored. In the vast majority of cases the detailed field information is
initialized automatically by SWIM in using information acquired via a corresponding VBA_SetAddr call and the SQL data
dictionary. Usage of an unbound control is the only case where the developer must fill in the detailed field information
manually since it will not exist in the SQL data dictionary.
The Struct.FieldName portion of the FieldName property must always be populated with a string value in the
bTableName.FieldName format. Using the above example, a control for the Acct field would have a value of
bAccount.Acct for the Struct.FieldName portion of its FieldName property. Similarly the Active control would have a
value of bAccount.Active for the Struct.FieldName portion of its FieldName property.
The first portion of this Struct.FieldName string, bAccount in our example, is used to link the control with a particular VBA_SetAddr
call that had the same value for its TableNameStr
argument. Once that initial linkage is made the exact memory location can be determined automatically by correlating the
last portion of the Struct.FieldName string, Acct or Active in our example, with the detailed field information acquired as
a result of the relevant
VBA_SetAddr call. In general, the VBA_SetAddr call facilitates the linkage of a bTableName.FieldName type of string
literal with a precise location in memory for the corresponding data value. The VBA_SetAddr statement uses the following
arguments:
bTableName User- VB variable whose datatype corresponds to the table referred to in the
defined TableNameStr argument. For example if bAccount is passed then the Visual Basic
datatype variable passed via this argument must be a user- defined datatype whose structure
precisely corresponds to the Account table in the database.
nTableName User- VB variable whose datatype corresponds to the table referred to in the
defined TableNameStr argument. If TableNameStr does not correlate to a database table then
datatype PNULL must be passed as the value for this argument. This value will be properly
initialized with null values as long as the relevant table is a database table. Any
structure of the relevant datatype can then be easily blanked out using the
bTableName = nTableName methodology.
bTableNameLength Integer Length (that is, size) of the entire bTableName user-defined type such as Len( bTableName).
Note: In Customization code, it is critical to use
LenB() instead of Len().
Microsoft Dynamics SL API Function Calls 197
The VBA_SetAddr statement is closely associated with the SAFUpdate control. The SAFUpdate
control is used to define logical groups of information on the screen via its Levels property as well as expose key database
and/or navigational events to the application such as OnCancel, NewLevel, OnDelete, OnFinish, and OnUpdate. All
applications have an SAFUpdate control on Form1. Properties of the SAFUpdate control are Customizable ( D), Index ( D), Left,
Levels ( D),
Name ( D), Tag, and Top. ( D means the property can be modified at design time only, not runtime.) Also refer to ApplGetReturnParms
and SqlCursor Statement.
Example
External .dh file
This declares a structure that matches the Microsoft Dynamics SL Country table. Note the exact size of the fields must be
declared and the buffer and NULL buffer structures are declared globally:
Type Country
CountryId As String * 3
Descr As String * 30
End Type
In Customization events:
(general) declarations
'$include: "cu\country.dh"
For Visual Basic customizations, add the .dh file to the VBA project.
Sub Form1_Load
Call VBA_Setaddr(" bcountry", bcountry, ncountry, LenB(bcountry)) Call Sqlcursor(c1, NOLEVEL) End Sub
See Also
FieldName Property
198 Customization Manager Reference Visual Basic for Applications
Glossary 199
Glossary
BSL
BSL.DH
A text format file in the Microsoft Dynamics SL program directory which contains global and function declarations for all
of the Microsoft Dynamics SL kernel functions that can be used in Basic Script Language.
call by reference
Arguments passed by reference to a procedure can be modified by the procedure. Procedures written in Basic are
defined to receive their arguments by reference. If you call such a procedure and pass it a variable, and if the procedure
modifies its corresponding formal parameter, it will modify the variable. Passing an expression by reference is legal in
Basic; if the called procedure modifies its corresponding parameter, a temporary value will be modified, with no apparent
effect on the caller.
call by value
When an argument is passed by value to a procedure, the called procedure receives a copy of the argument. If the called
procedure modifies its corresponding formal parameter, it will have no effect on the caller. Procedures written in other
languages such as C can receive their arguments by value.
comment
A comment is text that documents a program. Comments have no effect on the program (except for metacommands). In
Basic, a comment begins with a single quote, and continues to the end of the line. If the first character in a comment is a
dollar sign ($), the comment is interpreted as a metacommand. Lines beginning with the keyword Rem are also interpreted
as comments.
control ID
This can be either a text string, in which case it is the name of the control, or it can be a numeric ID. Note that control
IDs are case-sensitive and do not include the dot that appears before the ID. Numeric IDs depend on the order in which
dialog controls are defined. You can find the numeric ID using the DlgControlID function.
dialog control
An item in a dialog box, such as a list box, combo box, or command button.
function
A procedure that returns a value. In Basic, the return value is specified by assigning a value to the name of the function,
as if the function were a variable.
IntelliSense
Microsoft IntelliSense helps create error-free script statements by presenting you with the names of methods and
properties as soon as you have typed in the name of an object or API.
200 Customization Manager Reference Visual Basic for Applications
label
A label identifies a position in the program at which to continue execution, usually as a result of executing a GoTo statement.
To be recognized as a label, a name must begin in the first column, and must be immediately followed by a colon (:).
Reserved words are not valid labels.
metacommand
A metacommand is a command that gives the compiler instructions on how to build the program. In Basic,
metacommands are specified in comments that begin with a dollar sign ($).
name
A Basic name must start with a letter (A through Z). The remaining part of a name can also contain numeric digits (0
through 9) or an underscore character (_). A name cannot be more than 40 characters in length. Type characters are
not considered part of a name.
Object Model
A specification of the objects intrinsic to a given system, including a description of the object characteristics (attributes)
and a description of the static and dynamic relationships that exist between objects. In the case of Microsoft Dynamics SL
applications the Object Model is a collection of objects that collectively represent a screen.
precedence order
The system VBA uses to determine which operators in an expression to evaluate first, second, and so on. Operators
with a higher precedence are evaluated before those with lower precedence. Operators with equal precedence are
evaluated from left to right. The default precedence order (from high to low) is: numeric, string, comparison, logical.
procedure
A series of VBA statements and functions executed as a unit. Both subprograms ( Sub) and functions ( Function) are
called procedures.
subprogram
A procedure that does not return a value.
type character
A special character used as a suffix to a name of a function, variable, or constant. The character defines the data type
of the variable or function. The characters are: $ (Dynamic String), % (Integer), & (Long integer), ! (Single precision
floating point), # (Double precision floating point), @ (Currency exact fixed point).
vartype
The internal tag used to identify the type of value currently assigned to a variant. One of the following: 0 ( Empty), 1 ( Null),
2 ( Integer), 3 ( Long), 4 ( Single), 5 ( Double), 6 ( Currency), 7
(Date), 8 ( String), 9 ( Object).
Index D
data field 18 database 134, 150
database operations 172 database
update 183 DataTips 5 DateCheck
51, 64 DateCmp 51, 65
DateMinusDate 51, 66 DatePlusDays
* 51, 67 DatePlusMonthSetDay 51, 68
* . * 151
DateToInstlStr 69 DateToIntlStr 51
DateToStr 51, 69 DateToStrSep 51,
70 DBNavFetch 51, 71 debugging
@ tools 7 Default 13, 34 default data
value 34 Default event 34, 154
@ 144 Default property 34, 154 Delete 14,
29 DELETE 19 DELETE operation
35 Delete selection 77 Delete SQL
A statement 172 Deleted record 42
design time property 60 detail level
abort transaction 188, 189, 190 ActiveX 15 DIM 14 disable control 154
3 disabled object 157 DispFields 51,
ActiveX Controls 11 Add-In 73 DispForm 51, 74 Display 13, 40
Manager 12 aggregate function 17, Double 14 Dparm 51 DParm 75
163 AliasConstant 51, 55
ApplGetParms 51, 56
ApplGetParmValue 51, 57
ApplGetReturnParms 59
B
batch level 15 binding
195 BlankErr 23 bound
object 157
E
C Edit_Cancel 51, 76 Edit_Close 51,
76 Edit_Delete 51, 77 Edit_Finish
Call Stack 7 CallChks 51,
51, 78 Edit_First 51, 79 Edit_Last
63 Cancel selection 76
51, 80 Edit_New 51, 81 Edit_Next
character field 18 Chk
51, 82 Edit_Prev 51, 84 Edit_Save
13, 30 Click 13, 33 Click
52, 85 embedded screen object 13
event 36 Close selection
empty string 160 Enabled 23
76 Code Editor 5
Complete Word 5
G
General_Declarations 14
general-use routines 29 generic
code 118 GetBufferValue 52, 92
GetDelGridHandle 52, 93 M
GetGridHandle 52, 94
GetObjectValue 52, 95 GetProp macro level 36 margin
52, 96 GetSqlType 52, 98 indicator 6 Mask 26
GetSysDate 52, 99 GetSysTime master table 49 Max 27
52, 100 GLOBAL 14 Grid linechk MCallchks 52 MCallChks
29 Grid linegotfocus 29 GUI 13 106 MClear 52, 106
MClose 52, 107 MDelete
52, 108 MDisplay 52,
109
N
NameAltDisplay 53, 144 named parameter
section 57, 61 NEW 35 new record 165
New selection 81 Next selection 82
Normal level 30 NOTCHANGED 156, 186
null out 154 NULLDATE 65
S
SAFOption button 34 SAVE operation
38 Save selection 85 SaveTemplate
53, 150 screen event 1 SDelete 53,
151 SDeleteAll 53, 152 Select Case
Level 15 Select statement 17, 172
O SetBufferValue 53, 153 SetDefaults
object 13 53, 154 SetLevelChg 53, 156
Object Browser 8, 13 Object SetObjectValue 53, 153, 157 SetProp
Model 4 object type 13 OLE 53, 158 SetStatusBarText 53, 160
Controls 11 OnCancel 13, SFetch 53, 161 SGroupFetch 53, 163
29, 46 OnDelete 13, 35 SInsert 53, 165 Solomon.ini 61 sort
OnFinish 13, 29, 48 OnInsert order 124, 126, 128, 130 Sparm 53
13, 29, 49 OnUpdate 13, 29, SParm 167 sparse update error 169,
38 optimization flags 173 184 special structure 17 Sql 53 SQL
Option Explicit 14 168 SQL call 174 SQL data dictionary
195 SQL Select statement 134 SQL
Server API 172 SQL syntax 19
SqlCursor 53, 169 SqlCursorEx 53,
171 SqlErr 54, 174
P
parameter passing 57, 61, 104
parameter section 57 password 12
T
Tab Index property 118
TabIndex 27
table join 165, 178, 183 target
control 60
Template feature 145, 150
TestLevelChg 54, 186 TimeToStr
54, 187 toolbar text 160 ToolTip
160 TranAbort 54, 188 TranBeg
54, 189 TranEnd 38, 54, 190
TranStatus 54, 191 Trigger
property 30
U
unbound control 196
Update 14 UPDATE 19
Update event 15
V
validate 30 variable
15 variable type 14