我编写了一个Python脚本,该脚本从excel中获取表格数据,然后将其保存到word文档中。为此,我需要在excel中创建一个按钮来执行整个任务。这在python空闲或anaconda环境或Windows powershell上运行良好,但在VBA脚本或宏下则无法正常工作。我尝试了一切,但没有用。请帮帮我!
Untitled3.py
#!/usr/bin/env python
# coding: utf-8
# In[38]:
import pandas as pd
import docx
import os
from docx.enum.text import WD_BREAK
import xlwings as xw
import numpy as np
# In[39]:
xls = pd.ExcelFile('template2.xlsm')
aa=xls.sheet_names
b=len(aa)
aa
wb = xw.Book('template2.xlsm')
active_sheet_name = wb.sheets.active.name
active_sheet_name
# In[40]:
df=pd.read_excel('template2.xlsm',sheet_name=active_sheet_name)
# In[41]:
df1=df.iloc[4:,4:]
df1.columns=['Task Id','Project Name','Account Number','No. of hours']
# In[42]:
df1
# In[43]:
doc = docx.Document('test.docx')
t = doc.add_table(rows=df1.shape[0]+1, cols=df1.shape[1])
for j in range(df1.shape[-1]):
t.cell(0,j).text = df1.columns[j]
#for paragraph in doc.paragraphs:
# run = paragraph.add_run()
# run.add_break(WD_BREAK.PAGE)
# add the rest of the data frame
for i in range(df1.shape[0]):
for j in range(df1.shape[-1]):
t.cell(i+1,j).text = str(df1.values[i,j])
# save the doc
# In[44]:
doc.add_paragraph("\n")
#doc.add_paragraph("Month Name Can be given")
# In[45]:
doc.save('test.docx')
# In[46]:
f=open('test.docx','rb')
d=docx.Document(f)
#f.close()
os.startfile("test.docx")
# In[ ]:
代码1:
Dim Ret_Val
Dim args As String
args = "C:\Users\shiva\Desktop\Addingproject\Untitled3.py"
Ret_Val = Shell("C:\Users\shiva\AppData\Local\Programs\Python\Python37-32\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
MsgBox "Couldn't run python script!", vbOKOnly
代码2:
Sub Button2_Click()
rsp = Shell(Environ$("COMSPEC") & " /c C:\Users\shiva\Desktop\Addingproject\Untitled3.py", vbNormalFocus)
End Sub
它可以与anaconda或powershell一起正常工作,但不能与宏一起工作。在运行vba脚本时,命令提示符打开的时间约为0.01秒,并且未显示任何内容。我不知道发生了什么。