How do you copy worksheets with DispatchEx
? I can't copy from one worksheet from one workbook to another worksheet on another workbook. I am using DispatchEx
to open them in two separate excels. The line: ws1.Copy(Before=wb2.Worksheets(1))
is giving an error. This same line works for dispatch, but I need to open the files separately in excel.
import time, os.path, os
from win32com.client import DispatchEx
path1 = 'C:\\example1.xlsx'
path2 = 'C:\\example2.xlsx'
xla = DispatchEx("Excel.Application")
xla.DisplayAlerts = False
xla.Visible = True
xl = DispatchEx("Excel.Application")
xl.DisplayAlerts = False
xl.Visible = True
curTime = os.path.getmtime('C:\\example1.xlsx')
while True:
modTime = os.path.getmtime('C:\\example1.xlsx')
if(modTime > curTime):
wb1= xla.Workbooks.Open(Filename=path1)
wb2= xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws2 = xl.ActiveSheet
ws1.Copy(Before=wb2.Worksheets(1)) # problem code here. Works in
# dispatch
Here is what is below 'ws1.Copy(Before=wb2.Worksheets(1))' statement. The only difference is I am using Dispatch to open two workbooks in once instance. Doing it this way allows me to copy ws1 to wb2. But but the master file is closed, it will throw msg 'file available for editing', even though I specifiy wb1.close().
wb1.Close() #close wb1 but still get msg
#xla.Quit() #Quit() is the only way I can
#close out wb1 completely and
#not receive the 'file now
#available for edit' msg.
#But it close both books.
xla = Dispatch("Excel.Application") #starts up wb1 again if file
#is modified (path 1)
xla.DisplayAlerts = False
xla.Visible = True
This is the traceback I am getting: Ignore line 35 as some commented lines were not inserted here.
Traceback (most recent call last):
File "C:/Python34/updateExcel2Dispatch.py", line 35, in <module>
ws1.Copy(Before=wb2.Worksheets(1))
File "<COMObject <unknown>>", line 3, in Copy
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Office Excel', 'Copy method of Worksheet class failed', 'C:\\Program
Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)"