Server execution failed excel

  • Remove From My Forums
  • Question

  • Hi ,

    I’m using Excel.Application  generating excel report via vb.net 2003 , the problem is excel.exe process reminds even after  generated excel report closed  . I have been using  the followed code to close or dispose the process , but it does’nt  work either.

    thenks

    Dim procList() As Process = Process.GetProcesses()

    Dim k As Integer

    For k = 0 To procList.GetUpperBound(0) Step k + 1

        If procList(k).ProcessName = «EXCEL» Then

           procList(k).Close()

           procList(k).Dispose()

       End If

    Next

Answers

  • When all else fails I use API function calls:


    Declare Function FindWindow Lib «user32» Alias «FindWindowA» (ByVal lpClassName As String, ByVal lpWindowName As String) As Int32


    Declare Function PostMessage Lib «user32» Alias «PostMessageA» (ByVal hwnd As Int32, ByVal wMsg As Int32, _


    ByVal wParam As Int32, ByVal lParam As Int32) As Int32


    Public Function TerminateExcel()


    Dim ClassName As String = «XLMain»


    Dim WindowHandle As Int32

    Dim ReturnVal As Int32

    Const WM_QUIT = &H12

    Do

    WindowHandle = FindWindow(ClassName, Nothing)

    If WindowHandle Then

    ReturnVal = PostMessage(WindowHandle, WM_QUIT, 0, 0)

    End If

    Loop Until WindowHandle = 0

    End Function

I am trying to convert a .xls file to an .xlsx file on the server-side using Microsoft.Office.Interop.Excel.Workbook class as follows:

 workBook.SaveAs("FILENAME_HERE", XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

and I get the following error:

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). : System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
   at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
   at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
   at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at CALLING_METHOD_IN_MY_LIBRARY_HERE...

The problem is that this error occurs only on the staging server; on my local machine it works fine.

Things that I have tried on the staging server:

  1. **1) Run dcomcnfg open Component Services

2) Expand Component Services «->» Computer «->» My Computer «->» the DCOM configuration «

3) Find the «Microsoft Excel application.»

4) Right to open the Properties dialog box

5) Clicked on the «Security» tab,

6) «Launch and Activation Permissions, configure permissions, have added permissions — Identity run under Adminstrator user (This User), Interactive User and Launching Users

7). Launch and activation permissions + Access Permissions + Configuration Permissions => added IIS_IUSRS + Network Service with Full Controll**

2.
Changed the build of the project that converts the .xls file from «Any CPU» to «x86» on my local machine and published this library on the server.

Did someone figured out how to fix this problem? I am struggling on fix this issue for 2 days now.

Вопрос:

Я пытаюсь преобразовать файл .xls в файл .xlsx на стороне сервера, используя класс Microsoft.Office.Interop.Excel.Workbook следующим образом:

 workBook.SaveAs("FILENAME_HERE", XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

и я получаю следующую ошибку:

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). : System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at CALLING_METHOD_IN_MY_LIBRARY_HERE...

Проблема заключается в том, что эта ошибка возникает только на промежуточном сервере; на моей локальной машине он отлично работает.

Вещи, которые я пробовал на промежуточном сервере:

  • ** 1) Запустите dcomcnfg open Сервисы компонента

2) Разверните “Службы компонентов” → “Компьютер” → “Мой компьютер” → “Конфигурация DCOM”

3) Найдите “приложение Microsoft Excel”.

4) Чтобы открыть диалоговое окно “Свойства”

5) Нажмите на вкладку “Безопасность”,

6) “Разрешения запуска и активации, настройки разрешений, добавлены разрешения – Идентификация выполняется под пользователем Adminstrator (Этот пользователь), Интерактивный пользователь и запуск пользователей

7). Разрешения на запуск и активацию + Разрешения доступа + Разрешения для конфигурации = > добавлена ​​служба IIS_IUSRS + Network Service с полным контролем **

2.
Изменена сборка проекта, который преобразует файл .xls из “Любой процессор” в “x86” на моем локальном компьютере и опубликовал эту библиотеку на сервере.

Кто-нибудь понял, как исправить эту проблему? Я борюсь за исправление этой проблемы в течение 2 дней.

Ответ №1

Использование DCOMCNFG.exe. Откройте его и перейдите по ссылке:
Службы компонентов → Компьютеры → Мой компьютер → DCOM Config → Приложение Microsoft Excel.

Откройте свойства, выберите вкладку “Идентификация” и выберите интерактивного пользователя.

Ответ №2

Такая же проблема была решена для меня, “разрешив взаимодействие с рабочим столом” для службы. (в утилите tomcat6w config на вкладке “Вход в систему” )

Ответ №3

Попробуйте добавить метод Thread.Sleep, например Thread.Sleep(2000) в течение 2 секунд после workBook.open и workBook.SaveAs два метода. Если ваш файл Excel имеет много форматов, попробуйте продлить еще несколько секунд.

Hi,
I’m using a time scheduler system to open excels.
when the excels opens it does several things. at he ends it will finish by sending an email with and attachment and a range.
when I’m running the excel — the macros work fine but when Im using the trigger it gives me the server execution failed.
this is my macro :
Sub Mail_ActiveSheetTest()
‘Working in Excel 2000-2016
‘For Tips see: Excel Automation — Ron de Bruin
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim rng As Range

Set rng = Nothing
On Error Resume Next

With Application
.ScreenUpdating = False
.EnableEvents = False
End With

Set Sourcewb = ActiveWorkbook
ActiveWorkbook.ShowPivotTableFieldList = False
‘Copy the ActiveSheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook

‘Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
‘You use Excel 97-2003
FileExtStr = «.xls»: FileFormatNum = -4143
Else
‘You use Excel 2007-2016
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = «.xlsx»: FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = «.xlsm»: FileFormatNum = 52
Else
FileExtStr = «.xlsx»: FileFormatNum = 51
End If
Case 56: FileExtStr = «.xls»: FileFormatNum = 56
Case Else: FileExtStr = «.xlsb»: FileFormatNum = 50
End Select
End If
End With
Set rng = ActiveSheet.Range(«c12:eek:1160″).SpecialCells(xlCellTypeVisible)
On Error GoTo 0

If rng Is Nothing Then
MsgBox «The selection is not a range or the sheet is protected» & _
vbNewLine & «please correct and try again.», vbOKOnly
Exit Sub
End If

‘ ‘Change all cells in the worksheet to values if you want
‘ With Destwb.Sheets(1).UsedRange
‘ .Cells.Copy
‘ .Cells.PasteSpecial xlPasteValues
‘ .Cells(1).Select
‘ End With
‘ Application.CutCopyMode = False

‘Save the new workbook/Mail it/Delete it
TempFilePath = Environ$(«temp») & «»
TempFileName = «DailySetReport» & » » & Format(Now, «dd-mmm-yy»)

Set OutApp = CreateObject(«Outlook.Application»)
Set OutMail = OutApp.CreateItem(olMailItem)

With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.To = «SalesNYIL@Nirugroup.com»
.CC = «»
.BCC = «»
.Subject = «DailySetsReport » & Format(Now, «dd-mmm-yy»)
.Attachments.Add Destwb.FullName
.HTMLBody = RangetoHTML(rng)
.Send ‘or use .Display
‘You can add other files also like this
‘.Attachments.Add («C:test.txt»)
.Send ‘or use .Display
End With
On Error GoTo 0
.Close savechanges:=False
End With

‘Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Function RangetoHTML(rng As Range)
‘ Changed by Ron de Bruin 28-Oct-2006
‘ Working in Office 2000-2016
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$(«temp») & «» & Format(Now, «dd-mm-yy h-mm-ss») & «.htm»

‘Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With

‘Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With

‘Read all data from the htm file into RangetoHTML
Set fso = CreateObject(«Scripting.FileSystemObject»)
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, «align=center x:publishsource=», _
«align=left x:publishsource=»)

‘Close TempWB
TempWB.Close savechanges:=False

‘Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

i have the following references:
Visual basic for application
Microsoft excel 16 object library

Microsoft outlook 16 object library
ole automation
stock 2.0 type library

please help me out here i tried almost everything

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

OLE error code 0x80080005: Server execution failed — This error appears when generating excel file

OLE error code 0x80080005: Server execution failed — This error appears when generating excel file

(OP)

13 Nov 20 05:23

This error «OLE error code 0x80080005: Server execution failed» appears only on one user. But other users don’t encounter the problem. I tried to run on mine, I don’t encounter the problem. It’s frustrating. I checked the ODBC, it was all good. I made sure no excel ran in the background before running the excel-generating program.
I also checked if the user has access in creating files in the folder, it was also okay.
I also tried to run other programs that generate excel, it also popped up the same error. I don’t know what’s wrong with the user’s computer.

This is where the error I believe triggered:

CODE —> vfp

#Define xlEdgeBottom 9
#Define xlEdgeLeft 7
#Define xlEdgeRight 10
#Define xlEdgeTop 8
#Define xlDiagonalDown 5
#Define xlDiagonalUp 6
#Define xlNone -4142
#Define xlThin 2
#Define xlContinuous 1
#Define xlInsideHorizontal 12
#Define xlInsideVertical 11
#Define xlCenter -4108
#Define xlBottom -4107
#Define xlContext -5002
#Define xlRight -4152
#Define xlUnderlineStyleNone -4142
#Define xlLandscape 2
#Define xlAutomatic -4105
#Define xlSolid 1
#Define xlThemeColorDark1 1
oXLS = Createobject("Excel.Application")

With oXLS
	oWB = .WorkBooks.Add
*** some codes
Endwith 

Kindly help.

— webrider —

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

There are several reasons why this issue can occur. If you are getting this error, it means MATLAB is not able to connect to Excel due to some issue on your system. It is not a MATLAB error rather a Windows produced error. Please see the following possible reasons and troubleshooting steps for this issue: 

1. The Anti-Virus software (McAfree) may be creating an issue with MS Office. Please try disabling/repairing the anti-virus software and check if it resolves the issue.

2. In order to determine if the issue is with MATLAB or Excel please start Windows Powershell (click start, type ‘powershell’ and open Windows Powershell app). In power shell, please type this:

$excel= New-Object -ComObject excel.application

(If this produces an error then the issue is not due to MATLAB.)

3. It might also mean a corrupt installation of the MS Office Suite; you can verify if your office installation is corrupt in multiple ways:

  •  Download the attached ‘test.vbs’ file to your system and then right-click on this file and select «Open with command prompt» option. This should open an Excel session and write the string «Test value» into cell ‘A1’.(If it writes the value into excel without any error then their office installation is not corrupt)
  • Please try the following commands in MATLAB command window to check whether other office applications are working fine: 

word = actxserver(‘Word.Application’)

p = actxserver(‘PowerPoint.Application’)

4. If your office installation is corrupt, you can try to repair the Microsoft Office installation by opening the ‘Apps and Features’ window from the start menu, search for Microsoft Office application and click on it, then click the «Modify» option, and select > Quick Repair.

Then, execute the following command in ‘MATLAB’ command window:

excel = actxserver(‘Excel.Application’)

5. If your Office installation is corrupt and quick repair does not resolve the issue, then you will have to reinstall the MS Office software.

6. Sometimes the issue might be caused due to incorrect ‘actxserver’ function being called( or being shadowed by a user-defined function with the same name) especially when there are multiple versions of MATLAB on your system, we need to determine if the correct ‘actxserver.m’ is being used. To do so please enter the following command in your MATLAB command window:

7.    Re-Register the Excel Application: From a command prompt, please navigate to where the Excel.exe file is located and re-register the application. On a 64-bit machine, this is located (by default) under C:Program Files (x86)Microsoft OfficeOffice16

This can be done as shown below:

Type cmd in the START menu and it will show you “Command Prompt” as the best match to your search. Then right click on it and select “Run as administrator”. This should open a command prompt. Now, type the following:

  • CD
  • And hit ENTER
  • CD C:Program Files (x86)Microsoft OfficeOffice16
  • And hit ENTER
  • EXCEL.EXE –REGSERVER
  • And hit ENTER

8. If none of the above workarounds work out it means that there is an issue with your Windows profile and resetting it should resolve the issue.

Detailed Error Information

CO_E_SERVER_EXEC_FAILURE[1]

Message Server execution failed
Declared in winerror.h

HRESULT analysis[2]

Flags Severity Failure
Reserved (R) false
Origin Microsoft
NTSTATUS false
Reserved (X) false
Facility Code 8 (0x008)
Name FACILITY_WINDOWS[2][1]
Description The source of the error code is the Windows subsystem.[2][1]
Error Code 5 (0x0005)

Questions

Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE))

I am trying to convert a .xls file to an .xlsx file on the server-side using Microsoft.Office.Interop.Excel.Workbook class as follows: workBook.SaveAs(«FILENAME_HERE», XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, Type.Missing); and I get the following error: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due […] read more

Why am I receiving exception from Office’s Outlook library?

I have an application that calls Email hello = new Email(appropriate constructor); hello.Email_Send(); I’m receiving the exception: > Retrieving the COM class factory for component with CLSID > {0006F03A-0000-0000-C000-000000000046} failed due to the following error: > 80080005 Server execution failed (Exception from HRESULT: 0x80080005 > (CO_E_SERVER_EXEC_FAILURE)). from System.Runtime.InteropServices.COMException. using O […] read more

VirtualBox: issue with symlinks in shared folders

Some time ago there was a thread to exact the same problem: Can’t create symlinks in virtualbox shared folders. Now it’s closed (why?). So I start a new one, because I’ve got this issue now and cannot find a solution. Short issue description: By attepms to create/place a symlink in […] read more

.net interface to COM server fails with 0x80080005

I have a native c++ COM server that exposes COM interfaces. I can successfully use a native c++ client application to get and use the exposed interfaces from the server. When I use a .net client with a reference to the server, I get the error: > Retrieving the COM […] read more

VirtualBox command line error

I can run VirtualBox just fine, but when I run anything from the command line I get: VBoxManage.exe: error: Failed to create the VirtualBox object! VBoxManage.exe: error: Code CO_E_SERVER_EXEC_FAILURE (0x80080005) — Server execution failed (extended info not available) VBoxManage.exe: error: Most likely, the VirtualBox COM server is not running or […] read more

DCOM Failure of Office Automation

I developed a C# program that pulls data from a SQL Server database and then generates Word documents which include the data. I’ve set the program up to run as part of an SSIS job on a Windows Server 2003 box. The program runs as user SQLSVC which doesn’t have […] read more

Powershell cannot create Outlook COM object from Command Prompt

I have a script used to send mails via Microsoft Outlook from command prompt. This works fine if I run it from inside PowerShell or ISE console. But when I tried to execute same from classic Windows Command prompt (cmd.exe) even with Admin privileges, it was unable to create Outlook […] read more

Getting COMException when accessing Emails on Outlook 2010

Hello I am trying to access my emails in Outlook 2010 via a C# Console Application. Visual Studio is started with admin rights and I have added a reference to Microsoft.Office.Interop.Outlook v14.0.0.0 and used it as Outlook. My Code: Console.Write(«starting»); Outlook.Application app = new Outlook.Application(); Outlook.NameSpace mapiNameSpace = app.GetNamespace(«MAPI»); Outlook.MAPIFolder […] read more

Controlling iTunes with ASP.NET running under IIS

I’ve been trying to control iTunes with ASP.NET with varying levels of success, but none that fits my situation exactly. I’ve looked around the web and tried all of the provided solutions without much luck. I’ve tried using many different iTunes COM libraries (even the one that’s on Apple’s developer […] read more

Convert OpenXML SDK .docx files to PDF

I am filling a word template with data from the database, using OpenXML sdk 2.5 and i need to export the result in PDF. I am currently using a server-side Interop approach but from time to time I get the exception: > System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM > class factory […] read more

windows update broke windows subsystem for linux 2

I have been using Windows Subsystem for Linux 2, however after applying a Windows Update that had been waiting for a while, now when I open the Ubuntu terminal app, it is blank and I cannot type: * After leaving it open, it eventually outputs: Installing, this may take a […] read more

Appcrash KERNELBASE.dll error when I try to use Microsoft Office in Docker Container

I’m building a Docker Windows container with Microsoft Office 2013 using following Dockerfile: FROM microsoft/windowsservercore ## Setup package management. ENV chocolateyUseWindowsCompression=false RUN powershell -Command «iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex; Install-PackageProvider -Name chocolatey -Force» ## Installing office RUN powershell choco install officeproplus2013 —version 15.0.4827 -y ENTRYPOINT powershell When I try to […] read more

WatiN: Error opening Internet Explorer

I have a C# (Visual Studio 2010) project that opens Internet Explorer 8 like this: Brower browser = new WatiN.Core.IE( «http://google.com»); This used to work, but I had some problems that required me to reinstall Internet Explorer (I am on Window 7). I am using the .NET 4.0 framework (although […] read more

Multiple 12292 and 10 VSS errors

My server running Server 2003 R2 has been reporting multiple 12292 and 10 VSS errors when the UniTrends agent calls to the Shadow Volume Provider for a VSS Snapshot. The server has the latest updates including SP2. Thus far I have: • Checked vss writers using the vssadmin list writers […] read more

VirtualBox can not run as normal user.

I installed VirtualBox as administrator in windows 7, then I switch to a normal user, installed a Ubuntu in VirtualBox, it works fine for couple weeks, I usually use headless start virtual machine. But recently, I can not launch VirtualBox as a normal user anymore,either use command line or GUI, […] read more

Word Automation with ASP.NET

I have an old application that uses Microsoft Word automation in asp.net and I need to install it on a Windows Server 2012 R2 x64 with Office 2013 Standard x86. I know that Office automation in server technologies like IIS should be avoided but I don’t have the green light […] read more

Issue with opening Oracle VM Virtualbox in Windows 10

I have installed Oracle VM Virtalbox. I face the below error when i try to open the application error screenshot Failed to acquire the VirtualBox COM object. The application will now terminate. Completely failed to instantiate CLSID_VirtualBox: CO_E_SERVER_EXEC_FAILURE. Result Code: CO_E_SERVER_EXEC_FAILURE (0x80080005) Component: VirtualBoxClientWrap Interface: IVirtualBoxClient {d2937a8e-cb8d-4382-90ba-b7da78a74573} Note: If i […] read more

How to start AutoCAD from .NET, using Windows Service

I need to start AutoCAD from a windows service. This service is running with a «special» domain user, which is created for just running my service. This user is admin on the machine, and this user installed AutoCAD 2014 on the machine. The code I’m using to start AutoCAD 2014 […] read more

Using Outlooks COM class component fails only with admin privileges

I have a PowerShell script which queries the current Outlook session. Running it just in an unelevated PowerShell window works like expected, but when I’m in an elevated prompt it fails like demonstrated below: «normal» session: PS> New-Object -Com Outlook.Application Application : System.__ComObject Class : 0 Session : System.__ComObject Parent […] read more

Visual Basic code won’t open Microsoft Excel (Office 2010)

I’m trying to write some Visual Basic code in Visual Studio 2012 that will be able to open and make changes to an existing Microsoft Excel workbook (Office 2010). This is the code I’ve come up with: Dim BillingCalender As String = *Path to Excel Workbook* Dim xlsApp As Excel.Application […] read more

IIS cannot locate the Enterprise Architect Addin

I have a Web Application written in C# that uses allows the user to create diagrams and export them to Enterprise Architect. The plugin is also written in C# and built with the option Register for COM Interop. When I debug the application using Visual Studio 2015, it works without […] read more

How to start a AnyCPU compiled COM Server

I use a Microsoft example for a COM-Server: Out-of-process C# COM server (CSExeCOMServer) A simple Console COM Client should just start up the Server and use its Methods, Properties and Events. static void Main(string[] args) { Type type = Type.GetTypeFromCLSID(new Guid(SimpleObject.ClassId)); if (type == null) { throw new Exception(«ClientObject component […] read more

Word 2016 automation generates «error: 80080005 Server execution failed»

I have Office 2016 preview installed on a Windows 7 (Ultimate edition) developer machine along with VS 2010. I have the following simple C# WinForms application that attempts to create a Word document through automation: using Word = Microsoft.Office.Interop.Word; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public […] read more

Windows will not update at all (0x80080005)

I have already tried about everything there is to fix this and it still does not work. I refuse to just reinstall completely because I have no way to back up 400 gigabytes and Microsoft should just have a working product anyway. About half of everything on my PC is […] read more

Win10 WSL — No Ubuntu bootstrap when typing bash

I use Win10 Home edition; No special probs with the PC whatsoever; Software usually work fine, yet when I activate either CMD or Powershell and type bash, there’s no Ubuntu Bootstrap. This is a new problem: Never happened to me before in WSL… It basically started after I did an […] read more

How to overcome 80080005 Server execution failed error in io.filesystemwatcher

I have an io.filesystemwatcher set up in powershell to monitor and automatically process data. It passes every test so far, but randomly it yields the following: >> TerminatingError(New-Object): «Retrieving the COM class factory for component with CLSID {91493441-5A91-11CF-8700-00AA0060263B} failed due to the following error: 80080005 Server execution failed (Exception from […] read more

Application on IIS does not able to launch Adobe Illustrator

My application makes use of Adobe Illustrator on the server side to complete some routine tasks. It is working fine on IIS Express for development, however when it runs on IIS for production it throws the following error: System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {F66C7D88-4EEB-4A9B-BBF2-D229C9C46870} […] read more

COM class factory Error in Microsoft.Office.Interop

I get this Error in c# code: > Retrieving the COM class factory for component with CLSID > {000209FF-0000-0000-C000-000000000046} failed due to the following error: > 80080005 Server execution failed (Exception from HRESULT: 0x80080005 > (CO_E_SERVER_EXEC_FAILURE)). This is my code: Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); object miss = System.Reflection.Missing.Value; object […] read more

WiX behaving badly on XP machine with windows update issues

My WiX bundle behaves very badly on a specific XP machine (x86). It stalls for six minutes during the «initializing» phase (before any bundled installers are run). From the logs it seems extremely likely it is due to the dodgy state of windows update on the machine: [090C:0FC0][2018-03-27T19:31:17]i358: Pausing automatic […] read more

How to close outlook application opened by another user

I have a situation,I have an application which sends mail using OUTLOOK,problem is while I’m trying to send mails from the application which is opened as Administrator it throws exception > Retrieving the COM class factory for component with CLSID > {0006F03A-0000-0000-C000-000000000046} failed due to the following error: > 80080005 […] read more

MSProject COM Interop unstable behavior

We are extensively using COM Interop with MSOffice applications, and one of them — MSProject 2013, is behaving very unstable and strange. Sometimes it starts just fine, and works fine, but from time to time it is bugging us with following error: > Retrieving the COM class factory for component […] read more

WiX Toolset installs VC++ redistributable (x86) 2015 too slowly

I wrote a WiX Toolset Setup to install an application which requires the VC++ redistributable (x86) 2015. Everything works fine, but when vcredlist_x86.exe is launched, it installs the Package too slowly, it takers about six minutes ! If I run the vcredlist in standalone mode, it still takes six minutes, […] read more

C# — error while sending email from outlook

I have a C# exe which sends email from Outlook, it works fine if run manually. I am trying to run it through Task scheduler but it gives following error: System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server […] read more

What Does this Windows Update Fix for «Undoing Changes» Actually Do?

Trying to fix a «couldn’t complete the updates, undoing changes» issue (w/ error 0x80080005) on Windows 10. People have reported success with the registry edit in «step #4» here: https://www.repairwin.com/fix-windows-10-update-error-0x80070424/ I’m not opposed to trying such a fix, but would like to know what this actually does before running it. […] read more

Windows 10 update from 1803 to 1909 fails

My Windows 10 repeatedly fails to update. Today I decided to make a day of getting it to upgrade — and after a day of installing I’m no better off. The Windows Update tool fails and rolls back with no explanation, so I downloaded the ISO, mounted it, and ran […] read more

Error creating Excel.Application object System.Runtime.InteropServices.COMException

I got the next code in form application using vb in visual studio 2019, when i execute the sub cmd_data_Click i got the next error System.Runtime.InteropServices.COMException: ‘Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 […] read more

Powershell New-Object fails when run by Windows Task scheduler

I’m pretty sure that this must be some kind of weird permissions problem, but I haven’t been able to find anything that works. Here’s the problem: I have a PowerShell script that performs an FTP transfer to a remote site. It uses the CuteFTP transfer object. The script is called […] read more

Autohotkey sending mail through ComObject

Problem: I have made a script that sends a mail through ComObject and it works like a charm when i use it as user, but not if i execute it with Task Scheduler. ——————————————————————————— What have i done? I have changed ComObjActive to ComObjCreate. ——————————————————————————— Code: The body is correct […] read more

InteropServices.ComException error when trying to open a word doc in c#

When i run private void Print_Click(object sender, EventArgs e) { var application = new Microsoft.Office.Interop.Word.Application(); var document = new Microsoft.Office.Interop.Word.Document(); document = application.Documents.Add(Template: @»C:OfficeWordTemplatesAttNoteEN.dotm»); application.Visible = true; } i get the below message. i have the reference in for the office interop but i still get this message. > System.Runtime.InteropServices.COMException: […] read more

Create New Outlook 365 Email in PowerShell

I’m trying to create an Outlook email in PowerShell, and I’ve found the same code everywhere to do it: $ol = New-Object -comObject Outlook.Application $mail = $ol.CreateItem(0) $mail.Subject = «<Subject>» $mail.Body = «<Body>» and then either $inspector = $mail.GetInspector $inspector.Display() Or $mail.Display() to show the email. However, at the very […] read more

80080005 Server execution failed when using Word Automation

I have a .Net C# application that manipulates Word documents. I am using Microsoft.Office.Interop.Word.dll, part of Office 2010, product version 14.0.xxx. Invoking: using Microsoft.Office.Interop.Word; … Application app = new Application(); causes the following error: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: […] read more

Running outlook interlop by an application started with process.start

I know title is a little confusing. So my main problem is this: I have an application which updates an another app.And after update function ends it starts the other app with process.start method Process.Start(@»C:Program Files (x86)XMLMailServiceXMLMailWF.exe»); and this second updated program sends a mail with simple outlook interlop Microsoft.Office.Interop.Outlook.Application […] read more

An error occurred when attempting to search Windows Update

I use SSM document AWS-RunPatchBaseline to patch my windows servers. while trying to run it, I had this error with one of my servers: Invoke-PatchBaselineOperation : Exception Details: An error occurred when attempting to search Windows Update. Exception Level 1: Error Message: Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)) […] read more

Outlook VSTO Add-in — Load Error 80080005

I have an Outlook add-in and it works fine. But, on the Outlook loading, my add-in shuts down and i got an error > Retrieving the COM class factory for component with CLSID > {0006F03A-0000-0000-C000-000000000046} failed due to the following error: > 80080005 Server execution failed (Exception from HRESULT: 0x80080005 […] read more

Issue launching Outlook using Office Interop

I am building an ASP webforms application in C# and I am trying to launch Outlook to send an email from the client computer. I am using the following example, which I found online. public void sendEmail(object sender, EventArgs e) { // Create the Outlook application. Outlook.Application oApp = new […] read more

Can’t start VirtualBox manager. COM Object error

Our host is Windows Server 2008 r2. When a user RDP’s into the server and starts an instance of VirtualBox, then another user RDP’s in to a different user account and tries to start VirtualBox, it throws this error: > Failed to create the VirtualBox COM object. > Callee RC: […] read more

Error creating new outlook email from the server

I have a function that can create a new email in outlook and it works fine when running on my local machine. However, when deployed to the server i get the error shown below. This is what it looks like when I run the code on my local machine: Link. […] read more

.Net web app fails generating Excel workbook once on server, works perfectly in local

I’m just generating an excel workbook with the basic Microsoft.Office.Interop.Excel Here is the way the library is referenced in my project: > Copy Local: False > Embed Interop Types : True > Path: C:Program Files (x86)Microsoft Visual Studio 14.0Visual Studio Tools > for OfficePIAOffice14Microsoft.Office.Interop.Excel.dll > Runtime version: V2.0.50727 > Version: […] read more

Printing doc, docx, pdf, rtf and txt files from C# to network printer

I am required to print a file, of set formats (doc, docx, pdf, rtf and txt), to a software network printer, however I cannot find a way of printing these documents easily. I have already tried File.Copy(), but this fails — the printer wouldn’t handle the job. I tried this […] read more

workbook.SaveAs(Filepath) Not working in Staging env

I’m trying to delete empty rows and columns from excel when reading that Excel sheet. In my local environment working fine.In staging environment not working workbook.SaveAs() functionality.I have placed some log’s to read that log for trail and error method , After workbook.SaveAs() line the next log not reading.let me […] read more

app center in uwp causes server execution failed 0x80080005

I am using AppCenter in my uwp application and to use it I have following code in my app.xaml.cs constructor, just after initializecomponent() Code ( where exception occurs ) AppCenter.Start(«{appCenterSecret}», typeof(Analytics), typeof(Push), typeof(Crashes)); > Note that app was running fine for many days with this line of code before, > […] read more

How to fix docker daemon that will not restart due to hns error

* Docker for Windows Server * Windows Server version 1709, with containers * Docker version 17.06.2-ee-6, build e75fdb8 * Swarm mode (worker node, part of swarm with ubuntu masters) After containers connected to an overlay network started intermittently losing their network adapters, I restarted the machine. Now daemon will not […] read more

CO_E_SERVER_EXEC_FAILURE when trying to open PPT-File on CLIENT

Please note that this is NOT about a server — component or ASP.NET. This happens on a Client-Application (WinForms) I try to open a PPT-File from within my application. The following code works fine on my machine: _ppApp = new Microsoft.Office.Interop.PowerPoint.Application(); _ppApp.DisplayAlerts = PpAlertLevel.ppAlertsNone; _ppApp.SlideShowEnd += PpApp_SlideShowEnd; But at least […] read more

use Microsoft.Office.Interop.Excel.Application on IIS

I have a problem shelter my WebSite application on IIS. I tried to generate excel file using Microsoft.Office.Interop.Excel.Application, it work in debug but when i shelter my website on IIS, the generating file not work. I have a problem in the following instruction : Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); And […] read more

Retrieving outlook in asp.net web api Fail

I need to use Outlook API in my asp.net web api project. When I publish the project to local IIS server, VS need to run as administrator, so I run vs2015 as administrator but problem occurs as below: Exception Details: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID […] read more

Unable to execute dll remotely

I am quite new to C# application development. I have made a C# console application which I execute like this dotenet.exe <dll_name> This works fine when executed on the system. But I need to call this remotely. I am doing that through Powershell Invoke Command. But I am getting this […] read more

Unable to create an instance of CComPtr

I am trying to use a simple c++ out of process COM object, SimpleObject, with a console app I am writing using Visual Studio Community 2017 (15.3.5) and Windows 10, but I am unable to initialize my object. I am using an ATL project for SimpleObject with the simple object […] read more

Creating Excel file in Console Application

I have a C# console application and it is creating excel file and send mail to our customer. It’s working in test server but its not working in production server and we get this following error ; Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to […] read more

Why my code is not run without run as administrator visual studio?

I’m executing code(create bitvise ssh server -user) normally(without run as administrator visual studio) then give error like Retrieving the COM class factory for component with CLSID {730D6BA1-01B1-5074-7182-990EF773DB5F} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). while open application using run as administrator visual […] read more

NetOffice getting 80080005 Server execution failed

I’m trying to edit a Word document programmatically. However, when I debug and first try to create the Word.Application, I get > Retrieving the COM class factory for component with CLSID > {000209FF-0000-0000-C000-000000000046} failed due to the following error: > 80080005 Server execution failed (Exception from HRESULT: 0x80080005 > (CO_E_SERVER_EXEC_FAILURE)). […] read more

Outlook VSTO add-in 80080005 exception while looking up tasks

I have a VSTO add-in, that looks up an Outlook task by an EntryID or a Subject, and does some operations on it. One of the users logged the following error message from it: > Retrieving the COM class factory for component with CLSID > {0006F03A-0000-0000-C000-000000000046} failed due to the […] read more

Unable to create outlook email draft using powershell on Outlook application

Hi have requirement to prepare outlook email draft and open it in Outlook. I have created php form to run supply variables to a powershell wich invokes outlook methods and create the email. When I execute the powershell as below C:Windowssystem32WindowsPowerShellv1.0powershell.exe C:wampwwwbizopsprepare_email.ps1 >> C:wampwwwbizopslog.log It works perfectly. But when I […] read more

Interop-Outlook error on Teamcity

I have several project which requires me to connect an email account and retrieve data from email arrives. When running locally on my PC, everything works fine. I have Teamcity (latest version) installed on a Windows 2008 server. This is my code where it seems it fails: public void DeleteAllEmails(string […] read more

new Outlook.Application() thorws error if Outlook app is running

Hi I am having similar issue CreateObject on Outlook.Application fails on Outlook 2010 when Outlook is running under a different account but want customized solution. I want to sent email with attachment for which my code works but if OutLook app is already opened as desktop app, then I am […] read more

Interop.Word Class Execution Failure

I’m trying to debug a problem in a REST API I’ve built in .Net MVC. In it, I’m trying to use the Microsoft.Office.Interop.Word library to do document manipulation. My application works just fine on my local development box. But, when I run it on the server (after a publish), it […] read more

Invoke-Command create new object

I’ve got a problem to create new object with Invoke-Command: $a = ‘TEST’ Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock { param($a, $b, $c) $o = New-Object -ComObject Outlook.Application echo $a } -ArgumentList ($a, $b, $c) I’m getting the following error: La récupération de la fabrique de classes COM pour le […] read more

Automate Internet Explorer on Azure

I’m trying to automate Internet Explorer using WatiN library in a Web App hosted on azure. I’m getting the following exception when trying to create an instance of IE : > System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM > class factory for component with CLSID {0002DF01-0000-0000-C000-000000000046} > failed due to the following […] read more

Microsoft.Office.Interop.Excel Error with Windows Service

I’m creating a windows service that will create excel sheets, I’ve used Microsoft.Office.Interop.Excel but got this Exception Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE I’ve attached a photo here Exception photo attached public void insertIntoSheet(string Name, DataTable dt) { Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { //MessageBox.Show(«Excel is not […] read more

IIS ap.net COM error iTunes

I’m trying to write an app based on my iTunes Library. I don’t have any problem in dev environnement (iis or dev srver). But in prod i’ve got this error > Retrieving the COM class factory for component with CLSID > {DC0C2640-1415-4644-875C-6F4D769839BA} failed due to the following error: > 80080005 […] read more

Outlook Interop fails after upgrade to Windows 10

I have a .net client program which sends emails using Interop for Outlook. This works fine on thousands of PCs on all versions of Windows. But following upgrades to Windows 10 a very small number of clients fail on sending an email with the message ‘sendSystem.Runtime.InteropServices.COMException (0x80080005). Retrieving the COM […] read more

Sometimes System.Runtime.InteropServices.COMException (0x80080005)

I am calling a Function of a Service from a homepage. The strange thing is, this works for hours, then I do not change anything and suddenly I get the following exception: System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {00020906-0000-0000-C000-000000000046} failed due to the following error: […] read more

Retrieving the COM Class factory in IIS 7

I have an 32-bit COM+ Application. One instance taking about 200MB~ in memory. I’m using this COM-object in my ASP.NET MVC 4 Web-Application. Web-Application is 32-bit too. It’s works good enough at Debugging and at IIS 7. Problems starts when I need to create 5 and more COM instances simultaneously: […] read more

Issues while creating a VSTO Word Application

creating a new VSTO Word Application in almost all cases works. I use this line to create a new instance: var wordApplication = new Application {Visible = false} (Application is «Microsoft.Office.Interop.Word.Application») We do this a lot in unit tests and in some automations. But once or twice in around 1000 […] read more

Error exporting datatable to excel C#

I’m currently having as issue exporting my DataTable to Excel using Microsoft.Office.Interlope. > The error that comes up is «winform Additional information: Retrieving the COM > class factory for component with CLSID {00024500-0000-0000-C000-000000000046} > failed due to the following error: 80080005 Server execution failed (Exception > from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).» […] read more

Console app that interacts with Illustrator fails

I have created a C#, .Net 4.5 console application that, during its runtime, interacts with Adobe Illustrator. * Specifically, it gets/or loads an instance of Illustrator * Opens documents * Performs some actions * Saves and closes the document. This is all done using Interop.Illustrator * Everything works fine when […] read more

Outlook Exception code : 0xc0000005 Visual studio C#

I developed an application that allows you to recover files from emails from an Outlook mailbox. To help me in this task, I use the Interop.Microsoft.Office.Interop.Outlook library. We are using this executable on a Windows 2012 R2 server. When I run it manually it works perfectly. However when I create […] read more

Run a COM based c# console application from Windows Service (c#)

I have a problem with running a c# console application from windows service application by c# code. I use windows service as a background worker that runs a task (Quartz library) every time interval. Here a code of job that runs other c# console app ps = new ProcessStartInfo(batchRunnerPath); ps.UseShellExecute […] read more

Comments

Leave a comment

Sources

  1. winerror.h from Windows SDK 10.0.14393.0
  2. https://msdn.microsoft.com/en-us/library/cc231198.aspx

User contributions licensed under CC BY-SA 3.0

Hi,
I’m using a time scheduler system to open excels.
when the excels opens it does several things. at he ends it will finish by sending an email with and attachment and a range.
when I’m running the excel — the macros work fine but when Im using the trigger it gives me the server execution failed.
this is my macro :
Sub Mail_ActiveSheetTest()

Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim rng As Range

Set rng = Nothing
On Error Resume Next

With Application
.ScreenUpdating = False
.EnableEvents = False
End With

Set Sourcewb = ActiveWorkbook
ActiveWorkbook.ShowPivotTableFieldList = False
‘Copy the ActiveSheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook

With Destwb
If Val(Application.Version) < 12 Then

FileExtStr = «.xls»: FileFormatNum = -4143
Else

Select Case Sourcewb.FileFormat
Case 51: FileExtStr = «.xlsx»: FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = «.xlsm»: FileFormatNum = 52
Else
FileExtStr = «.xlsx»: FileFormatNum = 51
End If
Case 56: FileExtStr = «.xls»: FileFormatNum = 56
Case Else: FileExtStr = «.xlsb»: FileFormatNum = 50
End Select
End If
End With
Set rng = ActiveSheet.Range(«c121160″).SpecialCells(xlCellTypeVisible)
On Error GoTo 0

If rng Is Nothing Then
MsgBox «The selection is not a range or the sheet is protected» & _
vbNewLine & «please correct and try again.», vbOKOnly
Exit Sub
End If

‘Save the new workbook/Mail it/Delete it
TempFilePath = Environ$(«temp») & «»
TempFileName = «DailySetReport» & » » & Format(Now, «dd-mmm-yy»)

Set OutApp = CreateObject(«Outlook.Application»)
Set OutMail = OutApp.CreateItem(olMailItem)

With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.To = «»
.CC = «»
.BCC = «»
.Subject = «DailySetsReport » & Format(Now, «dd-mmm-yy»)
.Attachments.Add Destwb.FullName
.HTMLBody = RangetoHTML(rng)
.Send ‘or use .Display
‘You can add other files also like this
‘.Attachments.Add («C:test.txt»)
.Send ‘or use .Display
End With
On Error GoTo 0
.Close savechanges:=False
End With

‘Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Function RangetoHTML(rng As Range)

Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$(«temp») & «» & Format(Now, «dd-mm-yy h-mm-ss») & «.htm»

rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With

With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With

Set fso = CreateObject(«Scripting.FileSystemObject»)
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, «align=center x:publishsource=», _
«align=left x:publishsource=»)

‘Close TempWB
TempWB.Close savechanges:=False

‘Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

Понравилась статья? Поделить с друзьями:
  • Set filters excel vba
  • Servants of the word
  • Set fields in word
  • Serpent of the word
  • Set expressions fixed word groups