sexta-feira, 30 de julho de 2010

Função para deixar uma array de maneira aleatória

//Função para deixar uma array de maneira aleatória
// Chamada: RandomizeArray( seuArray )

Sub RandomizeArray(ArrayIn As Variant)

Dim cnt As Long
Dim RandomIndex As Long
Dim tmp As Variant

'only if an array was passed
If VarType(ArrayIn) >= vbArray Then

'loop through the array elements in reverse
For cnt = UBound(ArrayIn) To LBound(ArrayIn) Step -1

'select a random array index
RandomIndex = Int((cnt - LBound(ArrayIn) + 1) * _
Rnd + LBound(ArrayIn))

'cnt represents one array member
'index, and RandomIndex represents
'another, so swap the data held in
'myarray(cnt) with that in myarray(RandomIndex)
tmp = ArrayIn(RandomIndex)
ArrayIn(RandomIndex) = ArrayIn(cnt)
ArrayIn(cnt) = tmp

Next

Else

'The passed argument was not an
'array; error handler goes here

End If

End Sub

terça-feira, 27 de julho de 2010

Função para maximizar a janela ao abrir

function maxWindow(){
window.moveTo(0,0);
if (document.all){
top.window.resizeTo(screen.availWidth,screen.availHeight);
}else if (document.layers||document.getElementById){
if (top.window.outerHeight top.window.outerHeight = screen.availHeight;
top.window.outerWidth = screen.availWidth;
}
}
}

Renomear o nome da base notes

Dim s As New NotesSession
Dim dbCur As NotesDatabase
Set dbCur = s.CurrentDatabase
Dim sDirectoryPath As String
sDirectoryPath = Left( dbCur.FilePath, Len(dbCur.FilePath) - Len(dbCur.FileName) )




Function rename(dbase As NotesDatabase,newname As String)

'//seta o caminho da base a ser renomeada
fulldbase$ = dbase.FilePath

a = 1
Do
b=a
a = Instr(b+1,fulldbase$, "\")
Loop Until a = 0

fulldbpathwithoutnsf$ = Left$(fulldbase$,b)

'//perdendo o indice da base
Set dbase = Nothing
'//renomeando a base
Name fulldbase$ As fulldbpathwithoutnsf$ + newname + ".nsf"

End Function

Funções para trabalhar com listas

Function RemoveFromList (Value As Variant, ValueList As Variant)
Dim tmpValueList() As String
x = 0
Redim Preserve tmpValueList(x)
Forall vals In ValueList
If Not Value = vals Then
Redim Preserve tmpValueList(x)
tmpValueList(x) = vals
x = x + 1
End If
End Forall
RemoveValueFromList = tmpValueList
End Function

Function AddToList (Value As Variant, ValueList As Variant)
Dim tmpValueList As Variant
' Load the array element by element so that the datatype is preserved
Redim tmpValueList(Ubound(ValueList))
For i = 0 To Ubound(ValueList)
tmpValueList(i) = ValueList(i)
Next
' Determine if we are dealing with a new list, if absolutely no
values in the first entry, then add new value to 0
If Ubound(tmpValueList) = 0 And Cstr(tmpValueList(0)) = "" Then
x = 0
Else
x = Ubound(tmpValueList) + 1
End If
Redim Preserve tmpValueList(x)
tmpValueList(x) = Value
AddToList = tmpValueList
End Function

Function RemoveItemFromList (intItem As Integer, ValueList As Variant)
' *** intItem should be passed in zero based as well as ValueList
Dim tmpValueList() As Variant
Dim intItemCnt As Integer
' Init the temporary list
Redim tmpValueList(0)
intItemCnt = 0
For x = 0 To Ubound(ValueList)
If Not intItem = x Then 'Not equal, we must
keep this one in the list
Redim Preserve tmpValueList(intItemCnt)
tmpValueList(intItemCnt) = ValueList(x)
intItemCnt = intItemCnt + 1 ' Count the
items we have kept so that we can adjust the array properly
End If
Next
RemoveItemFromList = tmpValueList

End Function

Function EntryInList (Value As Variant, ValueList As Variant) As Integer
' This will return a 1 based value if the position in the list
EntryInList = 0
i = 1
Forall Entries In ValueList
If Entries = Value Then
EntryInList = i
Exit Function
End If
i = i + 1
End Forall
End Function

Function RemoveRangeFromList (intStartPos As Integer, intEndPos As Integer,
varInput As Variant) As Variant
Dim tmpList() As Variant
Dim intPosCnt As Integer
intPosCnt = 0
For i = 0 To Ubound(varInput)
If i < intStartPos Or i > intEndPos Then
Redim Preserve tmpList(intPosCnt)
tmpList(intPosCnt) = varInput(i)
intPosCnt = intPosCnt + 1
End If
Next
RemoveRangeFromList = tmpList
End Function

URL: http://searchdomino.techtarget.com/tip/0,289483,sid4_gci490542,00.html

Seleciona no checkbox/radio o valor passado como parametro

function checkOption(radioName, newValue){
var els = document.getElementsByName(radioName);
if (els.value){
if (els.value == newValue){
els.checked = true;
}
}
for (var i = 0; i < els.length; i++){
if (els[i].value == newValue)
els[i].checked = true;
}
}

Seleciona no combobox o valor passado como parametro

function selectOption(selectName, value) {
var select = document.getElementById(selectName);
var options = select.options;
for (var i = 0; i < options.length; i++) {
var option = options.item(i);
if(option.value == value) {
option.selected = true;
}
}
}

Seleciona todos os valores do ListBox

function selectAllListBox(formName, filterId) {
var check = document.getElementById("filter_" + filterId + "_all");
var select = document.getElementById("filter_" + filterId);
var selected = true;
var options = select.options;
var i = 0;
while (i < options.length && selected) {
var option = options.item(i);
selected = option.selected;
i++;
}
check.checked = selected;
}

Seleciona todos os valores do CheckBox

function selectAllCheckBox( filterId) {
var check = document.getElementById("filter_" + filterId + "_all");
var select = document.getElementById("filter_" + filterId);
var options = select.options;
for(var i = 0; i < options.length; i++) {
var option = options.item(i);
option.selected = check.checked;
}
}

Adiciona valor no combo e ordena

function addToComboboxInOrder(select, value, text) {
var option = document.createElement("option");
option.value = value;
option.innerHTML = text;
for (var i = 0; select.options.length; i++){
if (select.options[i].text.toLowerCase() > text.toLowerCase()){
select.insertBefore(option, select.options[i]);
return;
}
}
select.appendChild(option);
}

Adiciona valor no combo para seleção

function addToCombobox(select, value, text) {
var option = document.createElement("option");
option.value = value;
select.appendChild(option);
var _text = document.createTextNode(text);
option.appendChild(_text);
}

Verifica se existe o valor passado como parametro no combo

function hasItemCombobox(select, value) {
for (var i = 0; i < select.options.length; i++){
if (select.options[i].value == value){
return true;
}
}
return false;
}

Limpa combobox

function clearCombobox(select) {
select.options.length = 0;
select.disabled = false;
}

Função Split ( StringToArray )

Function StringToArray(textstr As String, delimiter As String) As Variant
' count is the counter for the number of array elements
Dim count As Integer
Dim ending As Integer
count = 0
'placeholder is used to mark the beginning of the string to be split
Dim placeholder As Integer
Dim splitstr As String
placeholder = 1
splitstr$ = delimiter
' txt$() is the array that will be returned
Dim txt$()
Redim txt$(0)
ending = Instr(placeholder, textstr, splitstr$)
'if ending = 0 then text does not contain a ; and the entire value should be returned
If ending = 0 Then
txt$(0) = textstr
End If
' do this until no more delimiters are found
While ending <> 0 And ending < Len(textstr) Redim Preserve txt$(count) txt$(count) = Mid$(textstr, placeholder, ending - placeholder ) count = count + 1 placeholder = ending + Len(splitstr$) ending = Instr(placeholder, textstr, splitstr$) If ending = 0 Then Redim Preserve txt$(count) txt$(count) = Mid$(textstr, placeholder, (Len(textstr)-placeholder) +1 ) End If Wend StringToArray = txt$ End Function ############################################################ ex.:call fcn_split(doc.campoA(0) + ";" + doc.campoB(0)) function fcn_split(chave As String) On Error Goto ops Dim formula As String Dim array As Variant '//gerando o array a partir da chave formula = {@Explode("} & chave & {";";")} array = Evaluate(formula) exit function #################################################### Function Split(sValue As String, sSeparador As String) As Variant '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 'Função Split(string, separador) -Transforma de uma String separada por um 'separador especifico em um Array de String do tipo Variant. ' Parâmetros: 'sValue(String) - Valores separados por um Caracter (Separador); 'sSeparador(String) - Separador que terá de ser encontrado na sValue 'Saída(Variant- Array ou String) - Se o método encontrar um separador na string, 'retornará um Array de String, senão retorna a String sem alterações. '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Dim aFile() As String Dim iCon As Integer Dim iPos As Integer Dim iPosIni As Integer Dim i As Integer iPos = Instr(sValue, sSeparador) If iPos = 0 Then Redim Preserve aFile(iPos+1) aFile(iPos) = sValue Split = aFile ' Split = sValue Else iPosIni = 1 While iPos <> 0
Redim Preserve aFile(iCon+1)
If IPos > iPosIni Then
aFile(iCon) = Mid$(sValue, iPosIni, iPos - iPosIni)
Else
aFile(iCon) = ""
End If

iPosIni = iPos+1
iPos = Instr(iPosIni, sValue, sSeparador)
iCon = iCon + 1
Wend

If iPosIni <= Len(sValue) Then Redim Preserve aFile(iCon+1) aFile(iCon) = Mid$(sValue, iPosIni, (Len(sValue) - iPosIni)+1) End If If Right$(sValue,1) <> sSeparador Then Redim Preserve aFile ( Ubound(aFile)-1)
Split = aFile
End If

End Function

Função para limpar campos do tipo combo ou text

function limpaCampo(campo){
var oList = document.getElementById(campo);
if ( oList.type =="select-one" || oList.type=="select-multiple" ) {
for (var i = oList.options.length - 1; i >= 0; i--){
oList.options[i] = null;
}
oList.selectedIndex = -1;
}else {
oList.value = ''; // campo texto
}
}

Ler contéudo dos campos no arquivo XML

ex.:
var descricao = pegaValor(item.getElementsByTagName("descricao")[0]);

function pegaValor(no){
if(no.childNodes.length>0){
return no.firstChild.nodeValue;
}else{
try{
return no.nodeValue;
}catch(e){
return " ";
}
}
}

OU:


function getElementText( xml, tagName ){
return xml.getElementsByTagName(tagName).item(0).text;
}

function getNodeValue(obj,tag){
return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}

Preview em um documento para impressão

function printpreview(){
var OLECMDID = 7;
var PROMPT = 1;
var WebBrowser = '';
document.body.insertAdjacentHTML('beforeBegin', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";
}

Função tulizada para criacao do objeto XMLHTTP

function getXmlHttp() {
try{
xmlhttp = new XMLHttpRequest();
}catch (ee){
try{
xmlhttp= new ActiveXObject("Msxml2.XMLHttp");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp=false;
}
}
}
return xmlhttp;
}

critica para qualquer tipo de campo

//o parametro flgCriticaHidden é opcional se quiser criticar mesmo que campo seja hidden

function isCampoPreenchido(objCampo, msgErro, flgCriticaHidden){

var flgOK = true;

//só critica se o objCampo existir no document
if(!objCampo){
return true;
}

//pega tipo do objCampo ou, caso tenha mais de um, do primeito elemnto do objCampo
var tipo = (objCampo.type ? objCampo.type : objCampo[0].type);

if(tipo=='hidden'){
//as vezes, é interessante que se o campo for hidden eu não critique,
//nesse caso é só passar false para flgCriticaHidden ou não passar
//nada, mas se eu quiser forçar a criticar é so passar o parâmetro
//como no caso de querer criticar campos de tabelas dinâmicas
if(flgCriticaHidden){ //se recebeu parametro e recebeu true
//se foi passado flag indicando que deve criticar HIDDEN
if(Trim(objCampo.value) == '') flgOK = false;
}else{
//só critica se o objCampo não for hidden
return true;
}
}else if(tipo=='select-one'){
//se o primeiro elemento da combo está selecionado, não está preenchido corretamente
if(objCampo.selectedIndex==0) flgOK = false;
}else if(tipo=='select-multiple'){
//inicialmente assumo que nenhum elemento do listbox está selecionado
flgOK = false;
for(var i=0; i //se algum foi selecionado considero preenchimento ok
if(objCampo.options[i].selected) flgOK = true;
}
}else if( (tipo=='radio') || (tipo=='checkbox') ){
//inicialmente assumo que nenhum elemento do checkbox ou radiobutton está checado
flgOK = false;
if(objCampo.length){
//caso exista mais de um checkbox/radio com esse nome, varro todos
for(var i=0; i //se algum foi selecionado considero preenchimento ok
if(objCampo[i].checked) flgOK = true;
}
}else if(objCampo.checked){
//caso só exista um checkbox/radio com esse nome, verifico se ele está checado
flgOK = true;
}
}else{ //text, textarea, file, ...
if(Trim(objCampo.value) == '') flgOK = false;
}

if(flgOK){ //se objCampo esta preenchido ok
return true;
}else{
if((msgErro)&&(msgErro!=null)&&(Trim(msgErro)!='')){
//exibe msgErro e põe foco no objCampo só se
//foi passada alguma msgErro com conteudo
alert(msgErro);
if(tipo!='hidden'){
if(objCampo.type)
objCampo.focus();
else
objCampo[0].focus();
}
}

return false; //objCampo não preenchido ok
}
}

Função para colocar o doc. pai em modo de leitura.

function LeituraDocPai(){
var f = window.opener.document.forms;
if(!f.elements){
var currHref = (window.opener.document.location.href);
var newHref = currHref.substring(0, currHref.indexOf("?"))+"?OpenDocument";
window.opener.location.href = newHref;
}
}

Função para voltar o doc em modo de leitura.

function Leitura(){
var f = document.forms;
if(!f.elements){
var currHref = (document.location.href);
var newHref = currHref.substring(0,currHref.indexOf("?"))+"?OpenDocument";
window.location.href = newHref;
}
}

Retorna a data atual formatada com dd/mm/aaaa

function dataatual() {
var hoje = new Date()
var dia = hoje.getDate()
var mes = hoje.getMonth()
mes = mes+1
var ano = hoje.getFullYear()
if (dia < 10)
dia = '0' + dia
if (mes < 10)
mes = '0' + mes

var dtatual = dia+'/'+mes+'/'+ano
return (dtatual);
};

COLLAPSE & EXPAND

function ExpColCateg(docnumber, view){

var form = document.forms[0].action.substring(0, document.forms[0].action.indexOf("?") + 9);
var url = window.location.href;
var strlen = url.length;
var before = url.indexOf("DocNum=");
var result = url.substring(before + 7 , strlen);
aux = "IMG" + docnumber;

// SE CLICAR EM EXPAND
if(url.indexOf("ExpandView") != -1){
window.open( form + "&Collapse="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}else{
// SE CLICAR EM COLLAPSE
if(url.indexOf("CollapseView") != -1){
window.open( form + "&Expand="+ docnumber + "&View=" +view +"&DocNum=" + docnumber , "_self") ;
}else{
// SE A ÚLTIMA AÇÃO FOR UM EXPAND
if(url.indexOf("Expand") != -1){
// SE O ÚLTIMO NÚMERO É O NÜMERO ATUAL
if(result == docnumber){
window.open( form + "&Collapse="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}else{
if(window.document.images[aux].src == location.protocol+"//"+location.host+ caminho +"/icon_epm_collapse.gif"){
window.open( form + "&Collapse="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ; }else{
window.open( form + "&Expand="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}
}
}else{
// SE A ÚLTIMA AÇÃO FOR UM COLLAPSE
if(url.indexOf("Collapse") != -1){
if(result == docnumber){
window.open( form + "&Expand="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}else{
if(window.document.images[aux].src == location.protocol+"//"+location.host+ caminho +"/icon_epm_collapse.gif"){
window.open( form + "&Collapse="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}else{
window.open( form + "&Expand="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}
}
}else{
// DEFAULT
if(url.indexOf("Collapse") == -1 && url.indexOf("Expand") == -1){
window.open( form + "&Expand="+ docnumber + "&View="+view +"&DocNum=" + docnumber ,"_self") ;
}else{
window.open( form + "&Collapse="+ docnumber + "&View="+view +"&DocNum=" + docnumber , "_self") ;
}
}
}
}
}
}

validar cpf

function valida_cpf(cpf) {

for(i=0;i cpf = cpf.replace(".","");
cpf = cpf.replace("-","");
}

var rcpf1 = cpf.substr(0,9);
var rcpf2 = cpf.substr(9,2);
var d1 = 0;

for (i=0;i<9;i++) {
d1 += rcpf1.charAt(i)*(10-i);
d1 = 11 - (d1 % 11);
}

if (d1>9) d1 = 0;

if (rcpf2.charAt(0) != d1) {
return false;
}

d1 *= 2;

for (i=0;i<9;i++) {
d1 += rcpf1.charAt(i)*(11-i);
d1 = 11 - (d1 % 11);
}
if (d1>9) d1 = 0;

if (rcpf2.charAt(1) != d1) {
return false;
}

return true;
}

Função Propercase

function toProperCase(s){
var i;
var returnString = "";
var tmpS=s.value.toLowerCase();
var arrS= new Array();
var arrS2 = new Array();
//search each word in array arrS
arrS=tmpS.split(" ");
for (i = 0; i < arrS.length; i++){
var thisWord=arrS[i];
//Check to see if word contains a hyphen
if(thisWord.indexOf("-")!=-1){
arrS2 = thisWord.split("-");
for(var j=0; j < arrS2.length; j++){
var thisWord2=arrS2[j];
returnString = returnString + thisWord2.charAt(0).toUpperCase() + thisWord2.substring(1,thisWord2.length)+"-";
}
returnString = returnString.substring(0,returnString.length-1)+" ";
} else {
returnString = returnString + thisWord.charAt(0).toUpperCase() + thisWord.substring(1,thisWord.length)+" ";
}
}
returnString = returnString.substring(0,returnString.length-1);
s.value = returnString;
}

Formatar CPF

Verifica se a data é maior ou igual

Ex:

dtselecionada = document.getElementById('campodata').value;

if (datamaior(dataatual(),dtselecionada)){
alert( 'A data selecionada não pode ser menor que a data atual!');
return false;
}



function dataatual() {
var hoje = new Date()
var dia = hoje.getDate()
var mes = hoje.getMonth()
mes = mes+1
var ano = hoje.getFullYear()
if (dia < 10) dia = '0' + dia if (mes < 10) mes = '0' + mes var dtatual = dia+'/'+mes+'/'+ano return (dtatual); }; function datamaiorigual(dt1,dt2){ var hoje = new Date(); var ano = hoje.getYear(); if(ano >= 50 && ano <= 99) ano = 1900 + ano else ano = 2000 + ano; var pos1 = dt1.indexOf("/",0) var dd = dt1.substring(0,pos1) pos2 = dt1.indexOf("/", pos1 + 1) var mm = dt1.substring(pos1 + 1,pos2) var aa = dt1.substring(pos2 + 1,10) if(aa.length < 4) if(ano > 1999)
aa = (2000 + parseInt(aa,10))
else
aa = (1900 + parseInt(aa,10));
var data1 = new Date(parseInt(aa,10),parseInt(mm,10) - 1, parseInt(dd,10));
var pos1 = dt2.indexOf("/",0)
var dd = dt2.substring(0,pos1)
pos2 = dt2.indexOf("/", pos1 + 1)
var mm = dt2.substring(pos1 + 1,pos2)
var aa = dt2.substring(pos2 + 1,10)
if(aa.length < 4) if(ano > 80 && ano <= 99) aa = (1900 + parseInt(aa,10)) else aa = (2000 + parseInt(aa,10)); var data2 = new Date(parseInt(aa,10),parseInt(mm,10) - 1,parseInt(dd,10)); if(data1 > data2)
return true;
else
return false;
}

Verifica se e-mail é valido

function emailCheck (emailStr) {
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
return false
}
}
return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
domArr[domArr.length-1].length>3) {
return false
}

if (len<2) {
var errStr="Este endereço de e-mail não possui um nome de Host!"
return false
}

return true;
}

Valida Data

function ValidacaoData(aDate) {
var monthDays = "101010110101";
var validDate = new String("");
var aDay, aMonth, aYear;
var aN, aMonthFlg;
validDate = aDate;

if( validDate.length != 10 ) { alert("utilizar a data com formato = (dd/mm/yyyy)."); return false; }

aDay = validDate.substring(0, 2);
aMonth = validDate.substring(3, 5);
aYear = validDate.substring(6, 10);

if( isNaN(parseInt(aDay)) || isNaN(parseInt(aMonth)) || isNaN(parseInt(aYear)) ) {
alert(" - Dia, mês e ano devem ser numéricos."); return false; }

aN = parseInt(aDay);
if( (aN < 0) || (aN > 31) ) { alert(" - O dia do mês de estar entre 1 e 31."); return false; }

if( (aMonth < 1) || (aMonth > 12) ) { alert(" - O mês deve estar entre 1 e 12."); return false; }

aMod = aYear % 4;
if( aMod == 0 ) aLim = 29;
else aLim = 28;

if( (aMonth == 2) && (aDay > aLim) ) { alert("Fevereiro, deste ano, tem " + aLim + " dias."); return false; }
aMonthFlg = parseInt(monthDays.substring(aMonth-1, aMonth));

if( (aMonthFlg == 0) && (aDay > 30) ) { alert("O mês tem somente 30 dias."); return false;
} return true;
}

#################################################################################

function validaData(pStr){
reDate = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
if (reDate.test(pStr)) {
//alert(pStr + " é uma data válida.");
return true
} else if (pStr != null && pStr != "") {
// alert(pStr + " NÃO é uma data válida.");
return false
}
}

funções Left , right e Mid

function Left(str, valor)
{
var i = 0;
var strLen = 0;
strLen = str.length;
for(i = 0; (i < strLen) && (str.charAt(i) != valor); i++) ;
return str.substr(0,i);
}

function Right(str, valor)
{
var i = 0;
var strLen = 0;
strLen = str.length;
for(i = 0; (i < strLen) && (str.charAt(i) != valor); i++) ;
i++;
return str.substr(i,strLen);
}

function Mid(campo,x,y){
var res;
if(x>0)
x = x-1;
if(x+y > campo.length)
y = campo.length
else
y = x + y;
res = campo.substring(x,y);
return res;
}

Formatar CNPJ

function FormatarCNPJ(src, mask)
{
var i = src.value.length;
var saida = mask.substring(0,1);
var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
{
src.value += texto.substring(0,1);
}
}

Valida CNPJ

function valida_cnpj(cnpj)
      {
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }

Valida todos os tipos de campos. Texto, Data, Numero, Radio, Check, Combo

function ValidaCampo(Campo,NomeCampo,TipoCampo){
if (TipoCampo == "Texto"){
if (document.getElementById(Campo).value ==""){
alert("Você deve preencher o campo " + NomeCampo);
return false
}else{
return true
}
}

if (TipoCampo == "Data"){
if(!validaData(document.getElementById(Campo).value)){
alert("Você deve preencher o campo " + NomeCampo);
return false
}else{
return true
}
}

if (TipoCampo == "Check"){
obj = document.getElementById(Campo)
if (obj.length > 0){
for (i=0 ; i { if (obj[i].checked){
return true
}
}
}else{
if (obj.checked){
return true
}
}
alert("Você deve selecionar uma opção no campo " + NomeCampo);
return false
}

if (TipoCampo == "Combo"){
objCombo = document.getElementById(Campo)
if (objCombo.options[objCombo.selectedIndex].text == "" | objCombo.options[objCombo.selectedIndex].text == "Selecione uma Opção"){
alert("Você deve selecionar uma opção no campo " + NomeCampo);
return false
}else{
return true
}
}

if (TipoCampo == "Radio"){
objRadio = eval("document.forms[0]." + Campo)
var flagRadio = 0;
for( var nPos = 0; nPos < objRadio.length; nPos++)
{
if( objRadio[nPos].checked){
flagRadio = 1;
}
}
if (flagRadio == 1){
return true
}else{
alert("Você deve selecionar uma opção no campo " + NomeCampo);
return false
}
}

if (TipoCampo == "Valor"){
objNumber = replace(replace(document.getElementById(Campo).value, ",",""),".","")
if (objNumber == parseInt( objNumber ) ){ return true;
}else{
alert("Você deve preencher o campo " + NomeCampo + " com caracteres monetários( Números, vírgula e pontos )");
return false;
}
}

if (TipoCampo == "Numero"){
objNumber = document.getElementById(Campo).value
if (objNumber == parseInt( objNumber ) ){ return true;
}else{
alert("Você deve preencher o campo " + NomeCampo + " com caracteres númericos.");
return false;
}
}
}

Trata a Mensagem "No Documents Found".

Funções chamadas no Envento OnLoad.

var noDocumentsFound = document.body.all.tags("H2");
var tagH2, textH2;

for (var i = 0; i < noDocumentsFound.length; i++){
tagH2 = noDocumentsFound[i];
textH2 = tagH2.innerText;
if (textH2.toLowerCase() == "no documents found"){
tagH2.innerHTML = '

Não foram encontradas .....
';
}
tagH2.style.display = "block";
}



function MudaMsg() {
var chkH = document.all.tags('h2') ;
if (chkH.length==1) {
document.all.vwEmbed.style.visibility="hidden";
document.all.texto.style.visibility="visible";
} else {
document.all.vwEmbed.style.visibility="visible";
document.all.texto.style.visibility="hidden";
}
}
}

Função para abrir um documento passando o ID, altura e largura

function abreDoc ( doc, altura, largura ) {
window.open('($All)/' + doc + '?OpenDocument','','toolbar=no location=no directories=no status=no menubar=no scrollbars=yes resizable=no width='+altura+' height=' + largura + ' top=10 left=10');

Função que faz o refresh do form.

function dominoRefresh() {
//Se o form está em modo de leitura e não tem nome re-load na URL
if( window.document.forms[0].name == "" ) {
window.location.reload(true);
return false;
} else {
// _doClick "Refresh fields on keyword change"
_doClick('$Refresh', this, null, null);
return false;

Coloca em edição o documento corrente.

function Editar(){
var f = document.forms;
//=== Verifica se o documento está em modo de Edição ===
if(!f.elements){
var currHref = (document.location.href);
var newHref = currHref.substring(0, currHref.indexOf("?"))+"?EditDocument";
window.location.href = newHref;
}
}

funções para excluir o documento

function Excluir(){

//=== Montando a URL de Retorno ===
var aux_url = location.protocol + "//" + location.hostname + caminho;
var acao = "/($All)/" + document.forms[0].DocID.value + "?DeleteDocument";
var url = aux_url + acao;
var wopener = window.opener.location.href;
//alert(wopener);

//=== Valida a Exclusão ===
if (confirm("Deseja excluir o documento? ")) {
window.location.href = url;
window.opener.location.href = wopener;
//window.opener._doClick('$Refresh','this',null);
window.close();
}
}


function excluirDoc(){
if(confirm('Confirma a exclusão?')){
var urlCorrente = new String(document.location);
var urlDelecao = '';
if(urlCorrente.indexOf('?') == -1 ){
urlDelecao = urlCorrente + '?DeleteDocument';
}else{
var vetTemp = new Array();
vetTemp = urlCorrente.split('?');
var urlSemQueryString = vetTemp[0];
urlDelecao = urlSemQueryString + '?DeleteDocument';
}
self.location = urlDelecao;
}
}

Verificar se o documento é novo

function isNewDoc()
{
url = window.location.toString();
url = url.toLowerCase();
if (url.indexOf("openform") == -1)
return false;
else
return true;
}

Verificar se o documento. esta em modo Editável

function isDocBeingEdited()
{
if (isNewDoc()) return true;

url = window.location.toString();
url = url.toLowerCase();
if (url.indexOf("editdocument") == -1)
return false;
else
return true;
}



//Verificar se o documento é novo
function isNewDoc()
{
url = window.location.toString();
url = url.toLowerCase();
if (url.indexOf("openform") == -1)
return false;
else
return true;
}

Retorna o caminho da base

var caminho;
caminho = window.location.pathname.substring(0, window.location.pathname.toLowerCase().indexOf(".nsf") + 4);
var caminho = window.location.pathname.substring(0, window.location.pathname.toLowerCase().indexOf(".nsf") + 4);

função Replace

function replace(s,velho,novo) {
nova_str = "";
cont=0;
tam= (s.length);
indice = tam - 1;
tam_velho = (velho.length);
indice_velho = tam_velho - 1;
if (tam < tam_velho ) {
nova_str = s;
} else {
while (cont <= indice-indice_velho) {
aux = "";
aux = s.substring(cont,cont+tam_velho);
if (aux == velho) {
nova_str += novo;
cont += (tam_velho);
if (cont > indice-indice_velho) {
nova_str += s.substring(cont,tam);
}
} else {
if (cont+tam_velho == tam) {
nova_str += s.substring(tam-tam_velho,tam);
} else{
nova_str += aux.charAt(0);
}
cont++;
}
}
}
return nova_str;
}

retorna o valor no formato Currency

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)){
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10){
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
num = num.substring(0,num.length-(4*i+3))+'.'+
num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + num + ',' + cents);
}

retorna o o valor selecionado em um campo do tipo radiobutton

function obtemValorRadio(campo) {
for (i = 0 ; i < campo.length ; i++) {
if (campo[i].checked) {
return campo[i].value;
}
}
return "";
}

Validação e Mascara de HORA

function validaHora(hora) {
if (hora.length == 0) {
return true;
}
if (hora.length != 8) {
return false;
}
if (hora.charAt(2) != ':' || hora.charAt(5) != ':') {
return false;
}
for (i = 0 ; i < hora.length ; i++) { if (i != 2 && i != 5) { if (isNaN(hora.charAt(i))) { return false; } } } var h = hora.substring(0,2); var m = hora.substring(3,5); var s = hora.substring(6,8); if (h > 23 || m > 59 || s > 59) {
return false;
}
return true;
}


########################################################################################


function Mascara_Hora(Hora){
var hora01 = '';
hora01 = hora01 + Hora;
if (hora01.length == 2){
hora01 = hora01 + ':';
document.forms[0].tx_hora.value = hora01;
}
if (hora01.length == 5){
Verifica_Hora();
}
}

function Verifica_Hora(){
hrs = (document.forms[0].tx_hora.value.substring(0,2));
min = (document.forms[0].tx_hora.value.substring(3,5));

estado = "";
if ((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59)){
alert('Hora no formato inválido!')
document.forms[0].tx_hora.focus();
return false;
}

if (document.forms[0].tx_hora.value == "") {
alert('Favor digite a hora!')
document.forms[0].tx_hora.focus();
return false;
}
return true;
}

Retorna a data atual com dia da semana mes e ano

function DataHoje(aData) {
// --> Define nome do mes
var nomeMes = new Array(12);
nomeMes[1] = 'Janeiro';
nomeMes[2] = 'Fevereiro';
nomeMes[3] = 'Março';
nomeMes[4] = 'Abril';
nomeMes[5] = 'Maio';
nomeMes[6] = 'Junho';
nomeMes[7] = 'Julho';
nomeMes[8] = 'Agosto';
nomeMes[9] = 'Setembro';
nomeMes[10] = 'Outubro';
nomeMes[11] = 'Novembro';
nomeMes[12] = 'Dezembro';
// --> Define o nome do dia da semana
var nomeSemana = new Array(7);
nomeSemana[1] = 'Domingo';
nomeSemana[2] = 'Segunda-Feira';
nomeSemana[3] = 'Terça-Feira';
nomeSemana[4] = 'Quarta-Feira';
nomeSemana[5] = 'Quinta-Feira';
nomeSemana[6] = 'Sexta-Feira';
nomeSemana[7] = 'Sábado';

var oDia = nomeSemana[aData.getDay()+1];
var oMes = nomeMes[aData.getMonth()+1];
var oAno = aData.getYear();
return oDia + ', ' + aData.getDate() + ' de ' + oMes + ' de ' + oAno;
}

função trim

function trim(sStr){
var iI = 0;
var iJ = 0;
var iTam = 0;
var sAux = "";

// Verifica string vazia
iTam = sStr.length;
if(iTam==0) return(sStr);

// Localiza primeiro caracter nao espaco
for(iI=0; iI= iTam) return("");

// Localiza ultimo caracter nao espaco
for(iJ=iTam - 1; iJ>=0; iJ--)
if(sStr.charAt(iJ)!=' ') break;

// Retorna do primeiro ao ultimo nao espaco
return(sStr.substring(iI,iJ+1));
}


OU

function Trim(str){
while(str.charAt(0) == (" ") ){
str = str.substring(1);
}
while(str.charAt(str.length-1) == " " ){
str = str.substring(0,str.length-1);
}
return str;
}

OU:

function LTrim(Texto) {
var NovoTexto = "";
for (var i=0; i < Texto.length; i++) { if (Texto.substr(i, 1) != " ") { NovoTexto = Texto.substr(i); break } } return NovoTexto; } function RTrim(Texto) { var NovoTexto = ""; for (var i = (Texto.length - 1); i > -1 ; i--) {
if (Texto.substr(i, 1) != " ") {
NovoTexto = Texto.substr(0, i + 1);
break
}
}
return NovoTexto;
}

function Trim(Texto) {
return LTrim(RTrim(Texto));
}

Crítica para campo radio e checkbox

function isCheckboxMarcado(checkbox){
if(checkbox.length){
for(var i=0; i if(checkbox[i].checked)return true;
}
}else if(checkbox.checked){
return true;
}
return false;
}
function isRadioMarcado(radio){
return isCheckboxMarcado(radio);
}

UrlEncode & UrlDecode

function URLEncode(txt) {
var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()";
var HEX = "0123456789ABCDEF";
var plaintext = txt;
var encoded = "";

for (var i = 0; i < plaintext.length; i++ ) {
var ch = plaintext.charAt(i);
if (ch == " ") {
encoded += "+";
} else if (SAFECHARS.indexOf(ch) != -1) {
encoded += ch;
} else {
var charCode = ch.charCodeAt(0);

if (charCode > 255) {
alert( "Unicode Character '" + ch +
"' cannot be encoded using standard URL encoding.\n" +
"(URL encoding only supports 8-bit characters.)\n"); encoded += "+";
}else{
encoded += "%"; encoded += HEX.charAt((charCode >> 4) & 0xF);
encoded += HEX.charAt(charCode & 0xF);
}
}
} // for
return encoded; }

function URLDecode(txt) {

var HEXCHARS = "0123456789ABCDEFabcdef";
var encoded = txt;
var plaintext = "";
var i = 0;
while (i < encoded.length) {
var ch = encoded.charAt(i);
if (ch == "+") {
plaintext +=" "; i++;
} else if (ch == "%") {
if (i < (encoded.length-2) && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
plaintext+= unescape( encoded.substr(i,3) );
i += 3; } else {
alert( 'Bad escape combination near ...' + encoded.substr(i) ); plaintext += "%[ERROR]"; i++; }
}
else { plaintext += ch; i++; }
} // while
plaintext; };

Ler parametros da url

function getURLParam(strParamName){

var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = "&" + strHref.substr(strHref.indexOf("?") + 1); //.toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
return strReturn;
},

Validação de Campo Numérico

function isNumber(campo){  
    campo.value = Trim(campo.value);  
    str = campo.value;  
    if ( isNaN(getNumber(str)) ){  
        alert ("O campo deverá ser apenas numérico");  
        campo.value = "";  
        campo.focus();  
        return false;  
    }  
    return true;  
}  


function SomenteNumero(e,campo,label){
var tecla=(window.event)?event.keyCode:e.which;
if((tecla > 47 && tecla < 58) || (tecla >95 && tecla<106)){
return true;
}else{
alert("Você deve preencher o campo " + label + " com caracteres numéricos.");
limpaCampo(campo);
return false;
}
}




function validacamponumerico( campo, NomeCampo ) {
objNumber = document.getElementById(Campo).value
if (objNumber == parseInt( objNumber ) ){ return true;
}else{
alert("Você deve preencher o campo " + NomeCampo + " com caracteres numéricos.");
return false;
}
}


function isValidNumberValue ( objTextControl, strFieldName)
{
var nRet = true;
var strValidNumber="1234567890,";

for (nCount=0; nCount < objTextControl.length; nCount++)
{
strTempChar=objTextControl.substring(nCount,nCount+1);
if ( strValidNumber.indexOf(strTempChar,0)==-1)
{
alert("O campo " + strFieldName + " aceita somente valores numéricos !");
return false;
}
}

return nRet;
}

segunda-feira, 26 de julho de 2010

Retorna uma lista ordenada alfabeticamente

Function QuickSortString(memberArray As Variant) As Variant
On Error Goto Erro
Dim k As Integer, i As Integer, j As Integer, h As Integer, r As Integer
Dim temp As String

'Set up for Shell sort algorithm
k= Ubound(memberArray)
h = 1
Do While h < k
h = (h*3)+1
Loop
h = (h-1)/3
If h > 3 Then
h = (h-1)/3
End If

'Shell sort algorithm
Do While h > 0
For i = 1+h To k
temp = memberArray(i)
j = i-h
Do While j >0
'Para ordenar datas é necessário trocar o UCase da comparação por Cdat.
If Ucase(memberArray(j)) >Ucase(temp) Then
memberArray(j+h) = memberArray(j)
memberArray(j) = temp
Else
Exit Do
End If
j = j-h
Loop
Next i
h = (h-1)/3
Loop


QuickSortString = memberArray
Exit Function

Erro:
Msgbox "ScriptLibrary - SortList/QuickSortString - Erro: " & Error & " na Linha: " & Erl
Exit Function

End Function

Comparação entre duas datas

'Função que recebe duas datas e compara se a 1ª é a 2ª data de acordo com o tipo de operação(Maior,Igual)!
'A função retorna False se a 1ª data for menor ou diferente que a 2ª

Function TestaData(data1 As String, data2 As String, operacao As String)

On Error Goto Erro
Dim datA As NotesDateTime
Dim datB As NotesDateTime
Dim datAStr As String
Dim datBStr As String
'Pega as datas de criação dos documentos
Set datA = New NotesDateTime(data1)
Set datB = New NotesDateTime(data2)

TestaData = False

Select Case Operacao
Case "Maior"
If Cint(Year(datA.LSLocalTime) >Year(datB.LSLocalTime)) Then
TestaData = True
Elseif Cint(Month(datA.LSLocalTime)) > Cint(Month(datB.LSLocalTime)) Then
TestaData = True
Elseif Cint(Day(datA.LSLocalTime)) > Cint(Day(datB.LSLocalTime)) Then
TestaData = True
End If
Case "Igual"
If Cint(Year(datA.LSLocalTime) = Year(datB.LSLocalTime)) And Cint(Month(datA.LSLocalTime)) = Cint(Month(datB.LSLocalTime)) And Cint(Day(datA.LSLocalTime)) = Cint(Day(datB.LSLocalTime))Then
TestaData = True
End If
End Select
Exit Function

Erro:
Msgbox "TestaData - Erro na linha: " & Erl & " Erro: " & Error
End Function

função recebe um vetor como parâmetro e retorna esse vetor sem elementos repetidos

Function UniqueVet(V1 As Variant) As Variant
'#### Essa função recebe um vetor como parâmetro
'#### e retorna esse vetor sem elementos repetidos

On Error Goto Ops

Dim V2() As String
Dim CountV2 As Integer
CountV2 = 0
Redim Preserve V2( 0 To 0 )

' Para cada elemento do vetor recebido...
For i%=0 To Ubound(V1)
FlagI% = 0
'Até que v1 seja igual a v2 ou v2 chegue ao fim
For j%=0 To Ubound(V2)
If(V1(i%)=V2(j%))Then
FlagI% = 1
Exit For
End If
Next
If FlagI%=0 Then
Redim Preserve V2( 0 To CountV2 )
V2(CountV2) = V1(i%)
CountV2 = CountV2 + 1
End If
Next
UniqueVet = V2

Exit Function

Ops:
Messagebox "Error na functino UniqueVet - " & Str(Err) & ": " & Error & " - line: " & Erl
End Function

Recebe uma Double e retorna no formato monetário

Function FormatCurrency(num As Double) As String

'*************************************************************************************
'Função que Recebe uma Double( Ex.:12345.86 ou -12345.86 ) e retorna esse valor
'tipo String formatado como monetário. ( Ex.:R$12.345,86 ou R$-12.345,86)
'*************************************************************************************


On Error Goto ops

Dim SstrNumInt As String
Dim sign As String
Dim x, ant, RoundNum, cents As String

sign = Left(num,1)
If sign<>"-" Then
sign = ""
End If

RoundNum = Round(num, 2)
ant= Cstr(Fix(RoundNum))
ant = SubstituiString(Cstr(ant),"-","")
virgulapos = Instr(Cstr(RoundNum),",")
TamanhoNum = Len(Cstr(RoundNum))
decimal = TamanhoNum - virgulapos
If ant = (Cstr(RoundNum))Then
cents="00"
Elseif decimal = 1 Then
cents= (Right(Cstr(RoundNum),2)+"0")
Else
cents= Right(Cstr(RoundNum),2)
End If

cents = SubstituiString(Cstr(cents),",","")

num = ant
SstrNumInt = Cstr(Fix(Round(num, 2)))

If num < 1000 Then
x = SstrNumInt
Else
If num >= 1000 And num < 10000 Then
x = Left(SstrNumInt,1) + "." + Right(SstrNumInt,3)
Else
If num >= 10000 And num < 100000 Then
x = Left(SstrNumInt,2) + "." + Right(SstrNumInt,3)
Else
If num >= 100000 And num < 1000000 Then
x = Left(SstrNumInt,3) + "." + Right(SstrNumInt,3)
Else
If num >= 1000000 And num < 10000000 Then
x = Left(SstrNumInt,1) + "." + Mid(SstrNumInt,2,3) + "." + Right(SstrNumInt,3)
Else
If num >= 10000000 And num < 100000000 Then
x = Left(SstrNumInt,2) + "." + Mid(SstrNumInt,3,3) + "." + Right(SstrNumInt,3)
Else
If num >= 100000000 And num < 1000000000 Then
x = Left(SstrNumInt,3) + "." + Mid(SstrNumInt,4,3) + "." + Right(SstrNumInt,3)
Else
If num >= 1000000000 And num < 10000000000 Then
x = Left(SstrNumInt,1) + "." + Mid(SstrNumInt,2,3) + + "." + Mid(SstrNumInt,5,3)+"." + Right(SstrNumInt,3)
End If
End If
End If
End If
End If
End If
End If
End If
FormatCurrency = Cstr(sign + Cstr(x) + "," + Cstr(cents))

Exit Function

ops:
Messagebox "Erro na função FormatCurrency - " & Str(Err) & ": " & Error & " - line: " & Erl

End Function

DbColumn em Ls

Function DbColumn(strServer As String, strDB As String, strView As String, column As String) As Variant

On Error Goto ops

Dim session As notesSession
Dim db As notesDatabase
Dim dbTmp As notesDatabase
Dim viewTmp As NotesView
Dim Nvcol As NotesViewEntryCollection
Dim ventry As NotesViewEntry
Dim col As notesViewColumn
Dim tmpArray() As Variant
Dim tmpcount As Long


Set session = New NotesSession
Set db = session.currentDatabase

If strServer = "" Then
strServer = db.Server
End If
If strDB = "" Then
Set dbTmp = db
Else
Set dbTmp = session.GetDatabase(strServer, strDB)
End If

If dbTmp Is Nothing Then
Msgbox "Base não encontrada ou não pode ser abertar"
DbColumn = ""
Exit Function
End If

Set viewTmp = dbTmp.GetView(strView)
If viewTmp Is Nothing Then
Msgbox "View não encontrada"
DbColumn = ""
Exit Function
End If

Call viewTmp.Refresh

Set Nvcol=viewTmp.AllEntries

If Nvcol.Count <> 0 Then
Set ventry = Nvcol.GetFirstEntry()
If (ventry Is Nothing) Then
DbColumn=""
Exit Function
End If

tmpcount=0
While Not (ventry Is Nothing)
Redim Preserve tmpArray(tmpcount)
' pega os valores na coluna
tmpArray(tmpcount) = Cstr(ventry.ColumnValues(column))
tmpcount=tmpcount + 1
Set ventry = Nvcol.GetNextEntry(ventry)
Wend
'Retorna o resultado
DbColumn = Arrayunique(tmpArray)
Else
DbColumn = ""
End If



sai:
Exit Function
ops:
Msgbox "Erro na função DbColumn na linha " & Erl & " do tipo " & Err & " " & Error
DbColumn = ""
Resume sai
End Function

DbLookup em Ls

Function DbLookup(strServer As String, strDB As String, strView As String, strKey As String, column As String) As Variant

On Error Goto ops

Dim session As notesSession
Dim db As notesDatabase
Dim dbTmp As notesDatabase
Dim viewTmp As NotesView
Dim Nvcol As NotesViewEntryCollection
Dim ventry As NotesViewEntry
Dim col As notesViewColumn
Dim tmpArray() As Variant
Dim Lista As Variant
Dim tmpcount As Integer



Set session = New NotesSession
Set db = session.currentDatabase

If strServer = "" Then
strServer = db.Server
End If
If strDB = "" Then
Set dbTmp = db
Else
Set dbTmp = session.GetDatabase(strServer, strDB)
End If

If dbTmp Is Nothing Then
Msgbox "Base não encontrada ou não pode ser abertar"
DbLookup = ""
Exit Function
End If

Set viewTmp = dbTmp.GetView(strView)
If viewTmp Is Nothing Then
Msgbox "View não encontrada"
DbLookup = ""
Exit Function
End If

Call viewTmp.Refresh

Set Nvcol = viewTmp.GetAllEntriesByKey(strKey,True)

If Nvcol.Count <> 0 Then
Set ventry = Nvcol.GetFirstEntry()
tmpcount=0
While Not (ventry Is Nothing)

If Isarray(ventry.ColumnValues(column)) Then
Lista = ventry.ColumnValues(column)

For y = 0 To Ubound(Lista)
Redim Preserve tmpArray(y)
tmpArray(y) = lista(y)
' Msgbox "valor encontrado = " & lista(y)
Next
Else
Redim Preserve tmpArray(tmpcount)
' pega os valores na coluna
tmpArray(tmpcount) = Cstr(ventry.ColumnValues(column))
' Msgbox "valor encontrado = " & Cstr(ventry.ColumnValues(column))
tmpcount=tmpcount + 1
End If

Set ventry = Nvcol.GetNextEntry(ventry)
Wend
'Retorna o resultado
DbLookup = Arrayunique(tmpArray)
Else
DbLookup = ""
End If

sai:
Exit Function
ops:
Msgbox "Erro na função Dblookup na linha " & Erl & " do tipo " & Err & " " & Error
DbLookup = ""
Resume sai
End Function

Retornar os parâmetro do querystring

Sub ExplodeQueryString(QueryString As String, AgentArgs List As String)

Dim Args As String
Args = RightStr(QueryString, "OpenAgent&")
ArgsList = Evaluate ({@Explode("} & Args & {"; "&")})
Forall Arg In ArgsList
ArgKey = LeftStr(Arg, "=")
ArgValue = RightStr(Arg, "=")
AgentArgs(ArgKey) = ArgValue
End Forall

End Sub

ReplaceSubstring em Ls

Function ReplaceSubstring( strSource As String, strSearch As String, strReplace As String) As String

If (strSearch = strReplace) Then
ReplaceSubstring = strSource
Exit Function
End If
Dim intBegin As Integer
intBegin = 1
Dim intPos As Integer
intPos = Instr( intBegin, strSource, strSearch )
While intPos > 0
strSource = Left$( strSource, Instr( intBegin, strSource, strSearch) - 1) + strReplace + Right$( strSource, Len( strSource) - Instr( intBegin, strSource, strSearch ) - Len( strSearch) + 1 )
intBegin = Instr( intBegin + Len( strReplace ) + 1, strSource, strSearch )
If intBegin > 0 Then
intPos = Instr( intBegin, strSource, strSearch )
Else
intPos = 0
End If
Wend
ReplaceSubstring = strSource
End Function

//////////////////////////////////////////////

Function ReplaceSubstring(text As String, tag As String, tval As String) As String
' Simple Search and Replace function with 3 arguments (if "tag" is not found, "text" will be returned unmodified)
' text : the text to search in
' tag : the existing text or string we are looking for in "text"
' tval : the value that will replace tag

While Instr(1, text, tag, 1) > 0
If Instr(1, text, tag, 1) = 1 Then
text$ = tval$ & Mid(text$, Instr(text$, tag$)+Len(tag$))
Else
text$ = Mid(text$, 1, Instr(text$, tag$)-1) & tval$ & Mid(text$, Instr(text$, tag$)+Len(tag$))
End If
Wend

ReplaceSubstring=text$

End Function

Left e right functions q retorna um valor passado pelo separador

Function LsLeftStr(OrigStr, LeftOf ) As String

' ***** return the string to the left of the separator
Dim Pos As Integer
Dim OrigStrLen As Integer

Pos = Instr( Lcase(OrigStr), Lcase(LeftOf) )
OrigStrLen = Len(OrigStr)

If pos>0 Then
LsLeftStr = Left( OrigStr, (Pos-1))
Else
LsLeftStr = OrigStr
End If

End Function



Function LsRightStr(OrigStr, RightOf ) As String

' ***** returns the value to the right of the separator
Dim Pos As Integer
Dim OrigStrLen As Integer
Dim RightOfLen As Integer

Pos = Instr( Lcase(OrigStr), Lcase(RightOf) )
OrigStrLen = Len(OrigStr)
RightOfLen = Len(RightOf)

If Pos>0 Then
LsRightStr = Right( OrigStr, OrigStrLen - (RightOfLen+Pos-1))
Else
LsRightStr = OrigStr
End If
End Function
If pos>0 Then
LeftStr = Left( OrigStr, (Pos-1))
Else
LeftStr = OrigStr
End If

End Function



Function RightStr(OrigStr, RightOf ) As String

' ***** returns the value to the right of the separator
Dim Pos As Integer
Dim OrigStrLen As Integer
Dim RightOfLen As Integer

Pos = Instr( Lcase(OrigStr), Lcase(RightOf) )
OrigStrLen = Len(OrigStr)
RightOfLen = Len(RightOf)

If Pos>0 Then
RightStr = Right( OrigStr, OrigStrLen - (RightOfLen+Pos-1))
Else
RightStr = OrigStr
End If
End Function

Função Escape

Retorna uma string codificada

Function RemoveCaracteresEspeciaisWeb(qString) As String
tempText = qString
arrayCharTrash = Split("%E1,%E2,%E3,%C1,%C2,%C3,%C9,%E9,%EA,%CD,%ED,%D3,%D4,%D5,%F3,%F5,%F4,%DA,%DC,%FA,%FC,%E7,%C7,%20,%23",",")
arrayCharOk = Split("á,â,ã,Á,Â,Ã,É,é,ê,Í,í,Ó,Ô,Õ,ó,õ,ô,Ú,Ü,ú,ü,ç,Ç, ,#",",")
For i = 0 To Ubound(arrayCharTrash)
tempText = Replace(tempText,arrayCharTrash(i),arrayCharOk(i))
Next
RemoveCaracteresEspeciaisWeb = tempText
End Function



Function LSescape(strIn As String) As String
Dim strAllowed As String
Dim i As Integer
Dim strChar As String
Dim strReturn As String

'These are the characters that the JavaScript escape-function allows,
'so we let them pass unchanged in this function as well.
strAllowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" & "@/.*-_"
i = 1
strReturn = ""
While Not (i > Len(strIn))
strChar = Mid$(strIn, i, 1)
If Instr(1, strAllowed, strChar) > 0 Then
strReturn = strReturn & strChar
Else
strReturn = strReturn & "%" & Hex$(Asc(strChar))
End If
i = i + 1
Wend
LSescape = strReturn
End Function


Function Escape(s As String) As String
%REM
Encodes a string to the "x-www-form-urlencoded" form, enhanced with the UTF-8-in-URL proposal. This is the official
standard to encode URL's to support any possible character set (all Unicode characters).
%END REM
 Dim result As String
 Dim i As Integer
 Dim c As Long
 
 For i = 1 To Len(s)
  c = Uni(Mid$(s, i, 1))
  If c = Uni(" ") Then
   result = result + "+"
  Elseif (c>=Uni("A") And c<=Uni("Z")) Or (c>=Uni("a") And c<=Uni("z")) Or (c>=Uni("0") And c<=Uni("9")) Then
   result = result + Uchr(c)
  Elseif c <= &H007f Then
   result = result + "%" + Hex$(c)
  Elseif c <= &H07FF Then
   result = result + "%" + Hex$(&Hc0 Or (c\64))
   result = result + "%" + Hex$(&H80 Or (c And &h3F))
  Else
   result = result + "%" + Hex$(&Hc0 Or (c\4096))
   result = result + "%" + Hex$(&H80 Or ((c\64) And &H3F))
   result = result + "%" + Hex$(&H80 Or (c And &H3F))
  End If
 Next
 Escape = result
End Function

Função Unescape

Decodifica uma string codificada com o método escape.

Function LSunescape(strIn As String) As String
Dim i As Integer
Dim strChar As String
Dim strReturn As String

i = 1
strReturn = ""
While Not (i > Len(strIn))
strChar = Mid$(strIn, i, 1)
If Not strChar = "%" Then
strReturn = strReturn & strChar
Else
i = i + 1
strChar = "&H" & Mid$(strIn, i, 2)
strReturn = strReturn & Chr$(Val(strChar))
i = i + 1
End If
i = i + 1
Wend
LSunescape = strReturn
End Function


Function UnEscape(s As String) As String


Dim L As String
Dim M As String
Dim R As String
Dim P As Integer

P% = Instr(s,"%")
If P%>0 Then
L$=Left$(s,P%-1)
M$=Mid$(s,P%+1,2)
R$=Right$(s,Len(s)-(P%+2))
UnEscape = L$ & Chr(Cint("&h" & M$)) & R$
If Instr(UnEscape,"%") Then UnEscape = UnEscape(UnEscape)
Else
UnEscape = s
End If

Exit Function

End Function


Function Unescape(Byval s As String) As String

Dim iPercent As Integer
Dim iPlus As Integer
Dim sL As String
Dim sM As String
Dim sR As String

iPercent = Instr(s,"%")
iPlus = Instr(s,"+")
If iPlus = 0 Then
If iPercent = 0 Then 'neither percent nor plus was found.
Unescape = s
Else 'plus not found, deal with percent
sL = Left$(s,iPercent-1)
sM = Mid$(s,iPercent+1,2)
sR = Mid$(s, iPercent+3)
Unescape = sL + Chr$(Cint("&h" & sM)) + Unescape(sR)
End If
Elseif iPercent = 0 Or iPlus < iPercent Then 'percent doesn't exist or plus comes before percent, deal with plus
sL = Left$(s, iPlus - 1)
sR = Mid$(s, iPlus + 1)
Unescape = sL + " " + Unescape(sR)
Else 'percent comes before plus, deal with percent
sL = Left$(s,iPercent-1)
sM = Mid$(s,iPercent+1,2)
sR = Mid$(s, iPercent+3)
Unescape = sL + Chr$(Cint("&h" & sM)) + Unescape(sR)
End If

End Function