使用 Python 在 Excel 中自动执行操作(单击菜单按钮,在 InputBox 中键入文本..)

Automate actions in Excel using Python (Click menu button, type text into InputBox..)

我想使用 Python 自动执行下面在 Excel 中引用的操作,但我找不到任何解决方案来解决我正在寻找的问题,这很奇怪,或者我可能找不到'找不到合适的关键字来优化我的搜索。

我设法找到的是如何 open/close 工作簿、执行宏和处理异常。

我仍然需要自动化的是:单击功能区中的菜单按钮,弹出一个表单,然后单击单选按钮,然后在 InputBox 中输入用户名和密码,然后单击确定。

下面引用的操作的屏幕截图:

Step1

Step2

Step3

Step4

到目前为止我的代码的快速浏览:

import os
import subprocess 
import sys
import win32com.client as win32 
import win32com
import json
import time  


f=open ('*ConfidentialPath*')
data=json.load(f)
Path_VBA =data['Path_VBA']

try:
    xl = win32.Dispatch("Excel.Application")
    wb=xl.Workbooks.Open(Path_VBA) 
    xl.visible = True
    time.sleep(5)
    xl.Application.Run("OpenWorkbook")
    time.sleep(5)
    xl.Application.Run("CloseWorkbook")
    time.sleep(5)
    xl.Workbooks(1).Close(SaveChanges=1) 
    xl.DisplayAlerts = True 
    xl.Application.Quit() 

except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        print(message)

xl.Application.Quit()
del xl

如有任何帮助或指导,我们将不胜感激。

阅读 pyautogui 的文档并将其应用到我的代码后,我已经设法完成了我需要做的所有操作:

  • 正在单击菜单按钮。
  • 正在将文本插入 InputBox。
  • 发送热键。

下面是我整理的代码的快速视图:

import os
import subprocess 
import sys
import win32com.client as win32 
import win32com
import json
import time  
import pyautogui
import pyautogui as pag
import pyautogui as pya
import pyautogui as py

#JSON FILE
f = open('C:\WORKSTATION\PYTHON-VBA\config.json')
data = json.load(f)
Path_VBA = data['Path_VBA']

#JSON path of images of buttons i want to click on stored in a folder
BoutonGenerer = data['BoutonGenerer']
BoutonBackOffice = data['BoutonBackOffice']
BoutonGenerer2 = data['BoutonGenerer2']

#JSON path of strings needed to authenticate stored in the config file
Username = data['USERNAME']
Password = data['PASSWORD']

try:
    pyautogui.FAILSAFE = False
    #Opening the file with os.StartFile
    os.startfile(Path_VBA)
    #Sleep function to suspend execution of the current thread
    time.sleep(8)
    #Locate function that looks for the image
    pyautogui.locateCenterOnScreen(BoutonGenerer)
    #Click function
    pyautogui.click(BoutonGenerer)
    time.sleep(4)
    pyautogui.locateCenterOnScreen(BoutonBackOffice)
    pyautogui.click(BoutonBackOffice)
    time.sleep(4)
    pyautogui.locateCenterOnScreen(BoutonGenerer2)
    pyautogui.click(BoutonGenerer2)
    time.sleep(4)
    #Type into fonction
    pyautogui.typewrite(Username)
    time.sleep(2)
    #Hotkey enter
    pyautogui.press('enter')
    time.sleep(2)
    pyautogui.typewrite(Password)
    time.sleep(2)
    pyautogui.press('enter')
    
#And lastly throw an exception if errors were found
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print(message)