I am creating a automation that copies information of a cell that is focused and saves to a variable. While it does work, when I try to use the keyboard library or the pyautogui write function to type the variable on Notepad document, it stops working when there are more than 2 or 4 characters. When I attempt to write a larger amount, like with 9 characters, it starts delaying/lagging. I do not know what to do as I have tried many libraries and none seem to work. All I need to do with the program is to write the variable on a Notepad document.
There is a function that copies the focused cell on excel and saves it to a global variable. After, it descends one cell using pyautogui. This is the current code I have:
import win32com.client as win32
import pyautogui
import global_variables
def copiar():
try:
excel = win32.GetActiveObject("Excel.Application")
except:
print("Excel not found.")
return
# Obter o nome da planilha ativa
workbook_name = excel.ActiveWorkbook.Name
# Se a planilha ativa não for a desejada, você pode abrir a planilha usando o seu caminho
if workbook_name != 'CONEMB_ZLE.xlsx':
# Exibe uma mensagem de aviso
print("Excel not found, open.")
return
# Tornar o Excel visível
excel.Visible = True
# Selecionar a planilha ativa
sheet = excel.ActiveSheet
# Obter o valor da célula selecionada
global_variables.valor_global = sheet.Application.Selection.Text
# Imprimir o valor
#print(global_variables.valor_global)
# Pressionar a tecla de seta para baixo no teclado
pyautogui.press('down')
This is the code that pastes the information on a Notepad document:
while True:
focus = pygetwindow.getWindowsWithTitle('CONEMB_ZLE - Excel')[0]
focus.activate()
copiar()
item = global_variables.valor_global
focus = pygetwindow.getWindowsWithTitle('transportadora - Bloco de notas')[0]
focus.activate()
print(item)
keyboard.write(item)
sleep(2)
keyboard.press('enter')
It starts at the Excel tab and copies the data. It then goes to the Notepad tab and writes the variable containing the data on the Notepad document.
It's pretty simple, you don't need to use the
keyboard.write()function, when you can just paste the variable in. Here, I decided to usepyperclip. When I tested the code, I noticed thatpyperclip.paste()didn't work in different apps beside the terminal, so I came up with a backup solution. First, copy the item to the clipboard:Then it's up to you how you want to paste it. In this case, you can use
keyboardto press 'ctrl+v':Alternatively, you may want to try to use
pyautogui.typewrite()if that fails:I think that the copy and paste method is most efficient however, and will probably fix the lag.