Ir para conteúdo
Fórum Script Brasil
  • 0

Projeto:Macro utiliza VB scripts


junior.mast

Pergunta

Bom dia!

Eu utilizo um macro que também tem um editor, opçao para usar scripts e configurar os comandos.

Macro é um programa que usa de comandos de mouse e teclado para realizar funções repetitivas.

mas esse macro possibilita ser programado.

Tenho uma boa noção de programação, já fiz curso de vb a anos atrás

mas atualmente me encontro com dificuldade de desenvolver esse projeto.

Minha idea é a seguinte.

As funções onde não precisa de uma "inteligência de programação" são comandos combinados de teclado e mouse. eu consigo fazer, mas preciso mesclar com scripts em partes onde o macro precisara buscar informções dentro de uma planilha aberta do excel etc...

o Projeto é o seguinte:

As funções que preciso criar em script

1.0) BOX > determina a variavel "nome" a ser trabalhada

2.0)buscar o texto da variavel "nome" na janela ativa e (usarei na posição onde estiver clickdown "x.y")

2.1)na hora de salvar o arquivo, no texto introduzir a variavel "nome".xls

2.2)abrir arquivo "nome".xls

2.3)focar a janela de "nome".xls

*** agora estamos dentro do excel. ***

3.0)preciso que meu macro faça a formataçao da tabela,

a maioria das coisas a ser feitas são iguais, e podem ser feitas através de comandos do macro de mouse e teclado.

mas existe uma variavel "linhas"

essa variavel vai ser definida pelo numero de nomes variavel "nome" encontrado em uma certa coluna

3.1)eu preciso que o macro selecione com o mouse (se possivel atraves de comando do excel" de "T" linha ate "a,b" coluna

e depois "descer" até linha "J" ate coluna "a",b"

"a","b" tem posiçoes fixas, são onde começa a primeira coluna ser selecionada e onde é a ultima coluna a ser selecionada.

"T" é a primeira linha e é fixa tambem, sempre estará no mesmo lugar

"J" é a varivavel.. isso quer dizer, de um lado para o outro terei sempre as mesmas posicoes.. o começo "não necessariamente a primeira linha do excel" tambem tem posicao fixa.

mas o numero de linhas para baixo é um variavel instavel, e chega no maximo a 120, mas suportar ate 200 seria segurança necessaria.

3.2)penso nessa possibilidade se não haver alguma função para selecionar no excel por exemplo se variavel "linhas" for = a 5 então

(busca referencia em um arquivo ou tabela) selecionar (no excel) de c3 até j18. não sei se isso é possivel mas facilitaria muito, e não precisariamos criar as funçoes com as variaveis do tópico (3.1)

e se for possivel, tambem seria util para realizar buscas da variavel "nome" dentro d um coluna pré determinada que o numero encontrado de vezes da variavel "nome" dentro da coluna definiria a variavel "linhas"

enfim o resto do processo pode ser feito "roboticamente" como eu digo rs..

sem auxilio de inteligencia virtual, apenas o processo "mecânico" que o macro disponibiliza

segue abaixo o nome do macro e a descrição para uso de comandos, e tambem alguns códigos de funções que retirei do site do fabricante.

espero contar com a ajuda da comunidade.

Aceito idéas para facilitar o projeto, espero que esse desafio proporcione aprendizado para todos

grato

Júnior


Aldo's Macro Recorder 4.0
Copyright 2001-2003 by Aldo Vargas - http://www.aldostools.com

-----------
DESCRIPTION
-----------

Use the following script commands to create simple but powerful macro scripts:

:SCRIPT BASIC COMMANDS
{script}<code>{/script} Where valid script commands are:
{repeat <n>} Repeat the macro <n> times.
Place this command at the end of the macro.
{wait <n>} Stop the macro execution for n milliseconds.
{button <n> <wait> at <x>,<y>} Click mouse button
rem or ' Remmark/comments
var = <expression> Assign an expression to a variable.
if <expr> then / elseif / else / end if Conditional execution.
do [[while/until] <expr>] / loop Repeat code.
runmacro <file> Run external macro file (in text format)
continue Stop macro script and continue executing the macro.
halt Stop macro execution.
wait <milliseconds> Pause macro execution
sleep <milliseconds> Pause macro execution (do not respond to events)
goto <label> Go to the with the label indicated. Label is a name with colon (label1:)
return <value> Returns an expression to the exec() funcion. Use to pass a value between macros.

:KEYBOARD COMMANDS
{setscroll on} or {setscroll off} Set Scroll Lock state
{setcapslock on} or {setcapslock off} Set Caps Lock state
{setnumlock on} or {setnumlock off} Set Num Lock state
SendKeys <keystrokes> Send special keys to a program.
vbSendKeys <keystrokes> Send special keys to a Windows program.
For syntax of the <keystrokes> parameter, refer to the reference file sendkeys.txt

:MOUSE COMMANDS
SetMousePos <x>,<y> Set mouse position
LeftClick <x>,<y> Left click mouse button
RightClick <x>,<y> Right click mouse button
DoubleClick <x>,<y> Double click mouse button
ClickDown <x>,<y> Click down mouse button
ClickUp <x>,<y> Click up mouse button
ClickMenu <hWnd>, <text> Click a menu item of a given application without move the mouse
click <hWnd>, <text> Click a control of a given application without move the mouse

:DISPLAY VALUES
MsgBox <text> [,<value>,<title>] Show a text.
msgbox2 <text> [,<value>,<title>] Show a text using new dialog
showmessage <text> Show message without stoping the macro execution
Open <file> Open a document or Windows application.

:CLIPBOARD COMMANDS
SetClipboard <expression> Assign an expression to clipboard.
clipboard.copy Copy selected text/object (Ctrl+C)
clipboard.cut Cut selected text/object (Ctrl+X)
clipboard.paste Paste clipboard (Ctrl+V)
clipboard.pastetext <filename> Paste the content of a text file
clipboard.clear Clear clipboard
clipboard.undo Undo (Ctrl+Z)
clipboard.selectall Select all (Ctrl+A)
clipboard.selectword Select word (Shift+Ctrl+Left)
clipboard.selectline Select line (Home+Shift+End)
Clipboard.selecteol Select until end of line (Shift+End)
Clipboard.selectbol Select until begin of line (Shift+Home)
Clipboard.selecteot Select until end of text (Shift+Ctrl+End)
Clipboard.selectbot Select until begin of text (Shift+Ctrl+Home)

:PROGRAM COMMANDS
AppActivate <Window Title> Set focus on an open window.
Start <file>,<window title> Open a document or Windows application, and wait for window title
Open <file> Open a document or Windows application.
Open <file>,<parameters>,<oper> Open an application with parameters
Shell <command> Execute a command line
Shellandwait <file>, <param> Open a document a wait until the document is closed
wait <Window Title> Wait for a window title.
waitwindow <Window Title> Wait for a window title indefinitely until the window is visible
waitclose <Window Title> Wait for a window title dissapear
PlaySound <filename> Play wave file
beep Produce a sound alert signal.

:FILE COMMANDS
SaveFile <filename>, <text> Save text expression in a file
AppendFile <filename>, <text> Append text expression to a file
writeini <file>,<section>,<key>,<value> Write setting in ini file
Print <file> Print a document if Print command is available.
file.copy <source>,<destination> Copy a file or folder
file.copynew <source>,<destination> Copy only new files
file.move <source>,<destination> Move a file or folder
file.movenew <source>,<destination> Move only new files
file.update <source>,<destination> Copy only different files and make a backup of replaced files
file.rename <source>,<destination> Rename a file in the same directory
file.delete <filename>, <beforedate> Delete a file. Allows wildcard. optional <beforedate>
file.kill <filename>, <beforedate> Delete permanently a file. Allows wildcard. optional <beforedate>
file.open <filename> Open a document or Windows application.
file.print <filename> Print a document if Print command is available.
file.save <filename>, <text/expr> Save text expression in a file
file.append <filename>, <text/expr> Append text expression to a file
file.topappend <filename>, <text/expr> Append text expression to the top of a file
file.print <filename> Print a document if Print command is available.
file.attrib <filename>, <value> Change file attributes: RHSA
file.emptyrecyclebin Delete permanently items in the Recycle Bin
file.shortcut <link>, <file>,<args> Create shortcut file
chdir <path> Change current directory
mkdir <path> Create a windows folder
rmdir <path> Remove an empty windows folder

:NETWORK COMMANDS
Open <url> Open or download a document or Windows application.
dial <text> Dial a Dial-up networking connection
printfile <url> Download and print an HTML document.
file.internetshortcut <file>,<url> Create internet shortcut file
sendmail <server>,<from>,<to>,<subj>,<body>,<file> Send an email using standard SMTP server
sendemail <to>,<subject>,<body>,<file> Send an email using Microsoft Office's Outlook
emailto <to>,<subject>,<body>,<file> Prepare an email using Microsoft Office's
Outlook, but do not send.

:CONTROL PANEL
Controlpanel.Display <N> Display Settings
Controlpanel.System <N> System Settings
Controlpanel.Software Add/Remove Programs
Controlpanel.Hardware Hardware Settings
Controlpanel.Hardwarewizard Hardware Wizard
Controlpanel.Hardwaresetup Hardware Setup
Controlpanel.Internet <N> Internet Options
Controlpanel.Keyboard <N> Keyboard Settings
Controlpanel.Modem Modem Settings
Controlpanel.Mouse Mouse Settings
Controlpanel.Sound <N> Sound and Multimedia Options
Controlpanel.Regional <N> Regional Options
Controlpanel.TimeDate <N> Date/Time Settings
Controlpanel.Odbc ODBC32 Settings
Controlpanel.Game <N> Gaming Options
Controlpanel.Telephone <N> Phone and Modem Options
Controlpanel.Accessibility <N> Accessibility Options
Controlpanel.Dialup Network and Dialup Connections
Controlpanel.Fax Fax Settings
Controlpanel.Findfast Find Fast Settings
Controlpanel.Infrared <N> Wireless Link
Controlpanel.Update Windows Update Settings
Controlpanel.Scanner Scanners and Cameras
Controlpanel.Power Power Options
Controlpanel.Network Network Settings
Controlpanel.Password Password Settings
Controlpanel.show Show Control Panel
Controlpanel.Printers Show Printers
Controlpanel.RecycleBin Open Recycle Bin
Controlpanel.MyComputer Open My Computer
Controlpanel.NetworkNeighborhood Diplays the computers on your network
Controlpanel.ScheduledTasks Show scheduled tasks
Controlpanel.fonts Show installed fonts
Controlpanel.WindowsFolder Open Windows Folder
Controlpanel.SystemFolder Open Windows System folder
Controlpanel.Desktop Open Desktop directory
Controlpanel.MyDocuments Open "My Documents" folder for current user
Controlpanel.MyPictures Open "My Pictures" folder
Controlpanel.Favorites Open Favorites folder
Controlpanel.History Open History folder
Controlpanel.Recent Open Recent folder
Controlpanel.SendTo Open SendTo folder
Controlpanel.StartUp Open StartUp folder
Controlpanel.Cache Open Temporary Internet Files folder
Controlpanel.Cookies Open Cookies directory
Controlpanel.administrativetools Open Administrative Tools
Controlpanel.dialupconnections Open Network and Dial-up Connections folder

:WINDOW COMMANDS
MoveWindow <hWnd>,<x>,<y>,<w>,<h> Resize and set new position of a window
Use hWnd = FindWindow("<window title>")
or use hWnd = WindowFromMouse()
SetWindowOnTop <hWnd> Set window always visible
SetWindowNormal <hWnd> Removes the always visible state
MaximizeWindow <hWnd> Maximize Window
MinimizeWindow <hWnd> Minimize Window
RestoreWindow <hWnd> Restore Window
HideWindow <hWnd> Hide Window
ShowWindow <hWnd> Show Window
Enablewindow <hWnd> Enable window/control
setwindowtransparency <hWnd>, <value> Set window transparency
SetWindowText <hWnd>, <text> Set text to window or control *Use with caution*
CloseWindow <hWnd> Close window *Use with caution*
SelectDesktop <number> Select virtual desktop (1-8)
Changeres <w>,<h>,<bits>,<filename> Change the screen resolution w x h.
Bits = 2, 8, 16 or 24.
if <filename> is entered, the resolution is changed
temporarily
lockwindows Show dialog for Lock a Workstation

:ADVANCED COMMANDS
DoEvents Force Windows to execute the Windows message queue
setpriority <filename>,<priority> Set Windows process priority to a program.
0=Normal, 1=High, 2=Real Time, 3=Idle, 4=Kill task
shutdown <"logoff/bye/reboot/ask"> Shutdown Windows (Be careful using this command)
SetRegistry <hkey>, <section>, <val> Set value in registry. Valid hKey values:
HKey_Classes_Root, HKey_Current_User, HKey_Local_Machine
ClearKeyboardBuffer Clear keyboard buffer
resetautorun Clear the internal autorun control list
delay <milliseconds> General delay between each command.
quickcalc Show QuickCalc window
PostMsg <hWnd>,<WinMsg>,<Parm1>,<Parm2> *Use with caution*
SendMsg <hWnd>,<WinMsg>,<Parm1>,<Parm2> *Use with caution*

:FILE FUNCTIONS
readline(<filename>) Read first/next line of a file. Use readline("") to reset the file pointer.
eof() Returns if readline function found end-of-file
readfile(<filename>) Returns file content
filelen(<filename>) File length
fileexists(<filename>) File exists?
filedate(<filename>) File modification date
fileattrib(<filename>) File attributes
filecompare(<file1>,<file2>) Test if two files are different (0) or identical (-1)
getpath(<text>) Get path from a file name
getfilename(<text>) Get file name without path
getextension(<text>) Get file extension
shortpath(<filename>) Short path of a file (Win3.x compatible file name)
direxists(<path>) Directory exists?
getspecialpath(<number>) Get path for special folders of Windows.
environ(<dos-variable>) Returns the value of an enviroment variable.
curdir() Current directory.
dir([<path>]) Find files in a given directory.
drivetype(<drive>) Disk drive type: 0=none, 1=diskette, 2=hd, 3=ram, 4=cd
drivename(<drive>) Disk drive name
drivesize(<drive>) Total disk drive size
drivefree(<drive>) Free space in a disk drive
findfile(<filename>,<drive>) Find a file in the disk drive

:INPUT FUNCTIONS
inputbox(<prompt>,<default>) Ask for a value.
inputbox2(<prompt>,<default>) Ask for a value using standard InputBox.
askyesno(<prompt>) Ask for yes/no.
askyesno(<prompt>) Ask for yes/no/cancel. Yes = -1, No = 0, Cancel = 2
showoptions(<title>,<opt1>,...<opt8>) Show options dialog. Returns the number of the selected option.
showlist(<filename>) Show a list of options from a text file. Returns the selected text.
showopen(<filter>,<title>,<path>) Show open dialog. Returns the selected file name.
showsave(<filter>,<title>,<file>,<path>) Show save dialog. Returns the selected file name.
browsefolder(<prompt>,<path>) Show browse folder dialog
capslock() Caps lock on?
numlock() Num lock on?
scrollock() Scroll lock on?
keystate(<key>) key state (< 0 = pressed)
return() Returns the last value from the Return command.
iif(<value>,<true-expr>,<false-expr>) Returns true or false expression, based on value
readini(<file>, <section>, <key>) Get value from ini file.
getregistry(<hkey>, <section>, <key>) Get value from registry. Valid hKey values:
HKey_Classes_Root, HKey_Current_User, HKey_Local_Machine

:WINDOW FUNCTIONS
isrunning(<filename>) Is an application running?
windowsdirectory() Windows directory
systemdirectory() Windows System directory
tempdirectory() Windows Temp directory
macropath() Macro Recorder directory
programfiles() Program Files directory
activewindow() Returns the hWnd of the window that has the focus
windowfrommouse() Find a window or control at mouse position. Returns hWnd.
findwindow(<window title>) Find a window by title. Returns hWnd.
findchildwindow(<hwnd>,<text>) Find a control or child window by caption. Returns hWnd.
iswindowenabled(<hWnd>) Returns true if a window or control is enabled
iswindowvisible(<hWnd>) Returns true if a window or control is visible
iswindowmaximized(<hWnd>) Returns true a window is maximized
iswindowminimized(<hWnd>) Returns true a window is minimized
mousex() Returns x coord of mouse
mousey() Returns y coord of mouse
screenwidth() Screen width in pixels
screenheight() Screen height in pixels
findclass(<text>) Returns the hWnd of a window class
classname(<value>) Returns the class name of a hWnd
getwindowtext(<hWnd>) Returns text of a window or control.
clsidexists(<section>,<key>) Returns if an specified component is registered in windows
isnt() Is running Windows NT/XP/2000/2003 OS?
freemem() Returns free physical RAM memory
totalmem() Returns total physical RAM memory
freevirtualmem() Returns free virtual memory
virtualmem() Returns total virtual memory

:NETWORK FUNCTIONS
geturl(<url>) Download file using HTTP or FTP protocols. Returns the file contect.
Use: Open <url> to download a file showing Open / Save As buttons.
computername() Computer name
username() Current Windows user
ip(<host name>) Returns IP address of a host name. Requires a DNS.
host(<ip address>) Returns host name from an IP address. Requires a DNS.
ping(<address>) Returns the response time
isconnectedtointernet() Returns if the computer is connected to the network

:STRING FUNCTIONS
instr(<start>, <txt>, <sub>) Find position of a subtext within a text, left to right (case insensitive)
instrrev(<txt>, <sub>) Find position of a subtext within a text, right to left (case sensitive)
instrb(<start>, <txt>, <sub>) Find position of a subtext within a text, left to right (case sensitive)
mid(<text>,<start>,<length>) Returns a substring
left(<text>,<length>) Returns left part of a string
right(<text>,<length>) Returns right part of a string
format(<expression>,<mask>) Format an expression. Example: format(1000, "#,##0.00") = 1,000.00
len(<text>) Length of text.
trim(<text>) Remove trailing spaces from text.
ltrim(<text>) Remove left spaces from text.
rtrim(<text>) Remove right spaces from text.
ucase(<text>) Returns text converted to upper case.
lcase(<text>) Returns text converted to lower case.
propercase(<text>) Returns text converted to upper case and lower case.
unicode(<text>) Returns text converted to unicode.
fromunicode(<text>) Returns text converted to the default code page of the system.
isnumeric(<expression>) Is the expression numeric?
val(<expression>) Returns value of a text.
chr(<value>) ASCII character
asc(<value>) ASCII value of a character
space(<length>) Returns a string with specified number spaces.
string(<length>,<text>) Returns a string with specified number characters.
strcomp(<value1>,<value2>) Compare two strings. Returns: v1 = v2 -> 0, v1 < v2 -> -1, v1 > v2 -> 1
clipboard() Returns current text in clipboard (if any).
str(<value>) Returns value as string
text2url(<text>) Returns an encoded url text
url2text(<text>) Returns a decoded url text
encrypt(<value>,<password>) Returns a text encrypted with a password.
decrypt(<value>,<password>) Returns a text dencrypted with a password.
param(<value>) Returns the Nth command line parameter passed to the executable of Macro.exe

:TEXT PROCESSING FUNCTIONS
csv(<txt>,<value>) Returns the Nth element in a line formated as comma separated value
replacetext(<txt>,<value>,<new>) Replace text value
replacelike(<txt>,<value>,<new>) Replace text value using pattern
getnextline(<text>) Returns first/next line of a text.
getnextline(<text>,<pos>,<sep>) Returns first/next line of a text starting from a position.
eot() Returns true if getnextline reached the End-of-Text position.
pos() Returns the current position of the pointer of getnextline.
gettext(<text>,<begin>,<end>) Returns the first/next text closed between two text expressions.
gettext(<text>,<begin>,<end>,<pos>) Returns the first/next text closed between two text expressions starting from a specified position
gettext(<text>,<begin>) Returns the first/next text after a text label expression.
eot2() Returns true if gettext reached the End-of-Text position.
getword(<value>,<text>,<default>,<sep>) Returns the Nth word in a string delimited by space or the <SEP> character specified.
exec(<value>) Execute a macro script and returns the value from Return command.
Use || as line separator.

:DATE FUNCTIONS
isdate(<expression>) Is the expression a date?
day(<date>) Day of a given date.
month(<date>) Month of a given date.
year(<date>) Year of a given date.
weekday(<date>) Day of week of a given date.
hour(<date>) Hour of a given time.
minute(<date>) Minute of a given time.
second(<date>) Seconds of a given time.
date() Current date.
date$() Current date with dashes.
time() Current time.
time$() Current time in 24 hours format.
timer() Current time in seconds from 12:00am.
ticks() Time Windows have been running in milliseconds
now() Current date and time.
datediff(<expr>,<date1>,<date2>) Calculates the time difference between two dates.

:MATH FUNCTIONS
eval(<value>) Evaluate a string expression. Example: eval("5+2")
rnd(<value>) Random number.
int(<value>) Integer value. No decimals.
hex(<value>) Hexadecimal
oct(<value>) Octal
abs(<value>) Absolute value. Returns positive value
sgn(<value>) Sign of value. -1, 0, 1
sqr(<value>) Square root
exp(<value>) Exponential e^x
log(<value>) Logarithm base e
sin(<value>) Sine
cos(<value>) Cosine
tan(<value>) Tangent
sec(<value>) Secant
cosec(<value>) CoSecant
cotan(<value>) Cotangent
arcsin(<value>) Arc Sine
arccos(<value>) Arc Cosine
arcsec(<value>) Arc Secant
atn(<value>) Arc tangent
arccosec(<value>) Arc Cosecant
arccotan(<value>) Arc Cotangent
hsin(<value>) Hyperbolic Sine
hcos(<value>) Hyperbolic Cosine
htan(<value>) Hyperbolic Tangent
hsec(<value>) Hyperbolic Secant
hcosec(<value>) Hyperbolic Cosecant
hcotan(<value>) Hyperbolic Cotangent
harcsin(<value>) Hyperbolic Arc Sine
harccos(<value>) Hyperbolic Arc Cosine
harctan(<value>) Hyperbolic Arc Tangent
harcsec(<value>) Hyperbolic Arc Cotangent
harccosec(<value>) Hyperbolic Arc
harccotan(<value>) Hyperbolic

:LOGICAL OPERATORS
not Returns true if the expresion is false
and Returns true if both expr1 and expr2 are true
or Returns true if either expr1 or expr2 is true
xor Returns true if expr1 is true and expr2 is false (or viceversa)
eqv Returns true if expr1 and expr2 are true or false
imp Returns false if expr1 is true and expr2 is false
like Returns true if expr1 match with the pattern given in expr2

:CONSTANTS
CR() Carriage return character
LF() Line Feed character
CRLF() Carriage return and Line Feed characters
tab() Tab character
empty() Returns empty string.
ff() Form Feed Character
quote() Double quote character (")
esc() Escape character
[/codebox]

esse tutorial acima são alguns comandos que o "help" apresenta para ter orientação

abaixo temos exemplo de scripts que baixei no site oficial.

"read a text line by line"

[codebox]
{script}
'-- initialize example text
'-- use text = readfile(<filename>) to read a real text file
text = "line 1" & crlf() & "line 2" & crlf() & "line 3" & crlf() & "line 4"

'-- show all lines
msgbox text, "Text"

do
'-- get each line of the text
line = getnextline(text)
'-- show line
msgbox line
loop until EOT()
{/script}

"Show command line parameters"


{script}
'-- Read command line parameters
a1 = param(1)
a2 = param(2)
a3 = param(3)
a4 = param(4)
a5 = param(5)

'-- Show command line parameters
msgbox2 "parm 1 = """ & a1 & """ (1)" & chr(13) & " parm 2 = """ & a2 & """ (2)" & chr(13) & " parm 3 = """ & a3 & """ (3)" & chr(13) & " parm 4 = """ & a4 & """ (4)" & chr(13) & " parm 5 = """ & a5 & """ (5)"
{/script}
[/codebox]

Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,3k
    • Posts
      652,4k
×
×
  • Criar Novo...