Microsoft Excel cannot access the file 'SegmentExport2_f7d153.xlsx'. There are several possible reasons The file name or path does not exist. The file is being used by another program.

Sangtani, Payal (CSW) 0 Reputation points
2024-11-16T15:02:51.11+00:00

when we open the excel getting permission issue .

first create function to create the macro then open it .getting error on xlWorkBook = xlApp.Workbooks.Open(MacroFolderPath + sTmpExcelFile).

Please find the below code.pleas ehelp me out.

Protected Function GetMacrosTemplate() As Result

	Dim result As New Result(True)

	Dim rr As New ReportRequest

	Dim rights As New PSRSystemRights(GetCurrentAccountID, Me.ParentID)

	Dim rev As New PSRProjectRevisionBO(Me.ParentID)

	Dim wsInfo As New PSROracleWSProjectInfoBO()

	Dim enumerator As IEnumerator = Nothing

	Dim blnOracleWSDataFound As Boolean = False

	Dim sProjectNumber As String = rev.ExternalAtts.sProjectNumber

	Dim projectInfoViaCallToOracleWebService As XmlDocument = GetProjectInfoViaCallToOracleWebService(sProjectNumber)

	Dim sTmpExcelFile As String = String.Empty

	Dim sTmpExcelFullFilePath As String = Settings.Miscellaneous.FKIL2005FileRepository

	Dim sTmpMacroExcelFile As String = String.Empty

	If (rights.IsOriginator Or CIntSpecial(rev.ExternalAtts.sProjectManagerAccountID) = GetCurrentAccountID()) Then

		canEditOrginatorProjectManger = True

	End If

	Dim nsmgr As New XmlNamespaceManager(projectInfoViaCallToOracleWebService.NameTable)

	nsmgr.AddNamespace("pro", "http://xmlns.oracle.com/pcbpel/psr/ebs/projectinfo")

	nsmgr.AddNamespace("env", "http://schemas.xmlsoap.org/soap/envelope/")

	Dim xmlnlist As XmlNodeList = projectInfoViaCallToOracleWebService.SelectNodes("env:Envelope/env:Body/pro:OutputParameters/pro:GET_TASK_DETAILS/pro:PROJECT_TASK_INFO/pro:Row", nsmgr)

	Dim g As Guid = Guid.NewGuid()

	Try

		enumerator = xmlnlist.GetEnumerator

		Do While enumerator.MoveNext

			Dim current As XmlNode = DirectCast(enumerator.Current, XmlNode)

			blnOracleWSDataFound = True

			wsInfo = New PSROracleWSProjectInfoBO()

			wsInfo.PSROracleWSProjectInfoGUID = g.ToString()

			wsInfo.PSRRevisionSegmentID = "0"

			wsInfo.PROJECT_NUMBER = current.SelectSingleNode("pro:PROJECT_NUMBER", nsmgr).InnerText.ToString.Trim

			wsInfo.SEGMENT_NUMBER = current.SelectSingleNode("pro:TASK_NUMBER", nsmgr).InnerText.ToString.Trim

			wsInfo.TASK_NAME = current.SelectSingleNode("pro:TASK_NAME", nsmgr).InnerText.ToString.Trim

			wsInfo.ORACLE_SALES_ORDER_NUMBER = current.SelectSingleNode("pro:ORDER_NUMBER", nsmgr).InnerText.ToString.Trim

			wsInfo.SHIP_FROM_ORG_CODE = current.SelectSingleNode("pro:SHIP_FROM_ORG_CODE", nsmgr).InnerText.ToString.Trim

			wsInfo.ITEM_COST = current.SelectSingleNode("pro:ITEM_COST", nsmgr).InnerText.ToString.Trim

			wsInfo.PLANNED_ORDER_PROGRESS_DATE = current.SelectSingleNode("pro:PLANNED_ORDER_PROGRESS_DATE", nsmgr).InnerText.ToString.Trim

			wsInfo.ACTUAL_ORDERED_DATE = current.SelectSingleNode("pro:ACTUAL_ORDERED_DATE", nsmgr).InnerText.ToString.Trim

			wsInfo.SHIP_DATE = current.SelectSingleNode("pro:SHIP_DATE", nsmgr).InnerText.ToString.Trim

			wsInfo.Save()

			wsInfo = Nothing

		Loop

	Finally

		If TypeOf enumerator Is IDisposable Then

			TryCast(enumerator, IDisposable).Dispose()

		End If

	End Try

	Try

		rr.ReportName = "/" & getCFD() & "/PSR/SegmentExport2"

		'rr.ExportTypeString = "excel"

		rr.ExportTypeString = "excelopenxml"

		rr.AddParameter("PSRProjectRevisionID", CStrSpecial(Me.ParentID))

		rr.AddParameter("TBDDate", CDateSpecial(PSRRevisionSegmentBO.kPSRRevisionSegmentBO_DefaultDate_TBD))

		rr.AddParameter("SystemAdmin", rights.SystemAdmin)

		rr.AddParameter("canEditOrginatorProjectManger", canEditOrginatorProjectManger)

		rr.AddParameter("canEditProductionScheduler", canEditProductionScheduler)

		rr.AddParameter("canEditProjectEngineer", canEditProjectEngineer)

		rr.AddParameter("canEditElectricalEngineer", canEditElectricalEngineer)

		rr.AddParameter("canEditSourcingScheduler", canEditSourcingScheduler)

		If blnOracleWSDataFound Then

			rr.AddParameter("OracleProjectInfoGUID", g)

		End If

		''rr.PushReportFileToBrowser(False) 'all Leads Report reports are NOT shareable!

		sTmpExcelFile = Path.GetFileName(rr.ReportName) & "_" & Left(System.Guid.NewGuid().ToString(), 6) & "." & rr.ExportTypeExtension.Replace(".", "")

		Dim GetGuid As String

		GetGuid = Left(System.Guid.NewGuid().ToString(), 6)

		If sTmpExcelFullFilePath.Trim.Length > 0 Then

			If sTmpExcelFullFilePath.Substring(sTmpExcelFullFilePath.Length - 1, 1) = "\" Then

				sTmpExcelFullFilePath = sTmpExcelFullFilePath.Substring(0, sTmpExcelFullFilePath.Length - 1)

			End If

		End If

		sTmpExcelFullFilePath += "\temp\"

		rr.PushReportFileToFileSystem(sTmpExcelFullFilePath & sTmpExcelFile)

#Region "START: Appling Macro"

		Dim fi As System.IO.FileInfo

		'Dim MacroFolderPath As String = HttpContext.Current.Server.MapPath("\backup\")

		Dim MacroFolderPath As String = HttpContext.Current.Server.MapPath("\main\Macros\")

		Dim MacroTemplateFolderPath As String = ConfigurationManager.AppSettings("MacroTemplateFolderPath")

		' Dim MacroTemplatefilepath As String = ConfigurationManager.AppSettings("MacroTemplateFilePath")

		Dim NewProductTypesDate As Date = CDateSpecial(ConfigurationManager.AppSettings("NewProductTypesDate"))

		Dim MacroTemplatefilepath As String = Nothing

		Dim dCreated As Date = CDateSpecial(Session("dCreated").ToString())

		If (dCreated >= NewProductTypesDate) Then

			MacroTemplatefilepath = ConfigurationManager.AppSettings("MacroTemplateFilePath")

		Else

			MacroTemplatefilepath = ConfigurationManager.AppSettings("MacroTemplateFilePathForOld")

		End If

		System.IO.File.Copy(sTmpExcelFullFilePath + sTmpExcelFile, MacroFolderPath + sTmpExcelFile)

		Dim TempMacroTemplatefilepath As String = MacroTemplateFolderPath & "ePSR Excel Task Template" & "_" & Left(System.Guid.NewGuid().ToString(), 6) & ".xltm"

		System.IO.File.Copy(MacroTemplatefilepath, TempMacroTemplatefilepath)

		Dim AppliedMacroTemplateFile As String = "ePSR Excel Task Template" & "_" & Left(System.Guid.NewGuid().ToString(), 6) & ".xltm"

		Dim AppliedMacroTemplateFilepath As String = MacroFolderPath + AppliedMacroTemplateFile

		Dim xlApp As New Excel.Application()

		'If xlApp IsNot Nothing Then

		'    xlApp.Quit()  ' Close Excel instance

		'End If

		Dim xlWorkBook As Excel.Workbook

		Try

			xlWorkBook = xlApp.Workbooks.Open(MacroFolderPath + sTmpExcelFile)

		Catch ex As Exception

		End Try

		Dim xlWorkSheet As Excel.Worksheet = Nothing

		xlWorkBook = xlApp.Workbooks.Open(TempMacroTemplatefilepath)

		xlApp.Run("Auto_open")

		xlWorkBook.SaveAs(AppliedMacroTemplateFilepath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLTemplateMacroEnabled)

		xlWorkBook.Application.Quit()

		xlApp.Quit()

		fi = New System.IO.FileInfo(sTmpExcelFullFilePath + AppliedMacroTemplateFile)

		If fi.Exists Then

		Else

			System.IO.File.Copy(MacroFolderPath + AppliedMacroTemplateFile, sTmpExcelFullFilePath + AppliedMacroTemplateFile)

		End If

		System.IO.File.Delete(MacroFolderPath + AppliedMacroTemplateFile)

		System.IO.File.Delete(MacroFolderPath + sTmpExcelFile)

		System.IO.File.Delete(TempMacroTemplatefilepath)

		Utilities.PushFileServerDocToBrowser(sTmpExcelFullFilePath & AppliedMacroTemplateFile, AppliedMacroTemplateFile)

#End Region

	Catch ex As Exception

		result.Succeeded = False

		result.AddMessage(ex.Message)

	End Try

	Return result

End Function
Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
2,047 questions
Access
Access
A family of Microsoft relational database management systems designed for ease of use.
420 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,760 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Q&A Assist
    2024-11-16T15:02:51.1266667+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    It seems you're encountering a permission issue when trying to open an Excel file with your macro. The error message indicates that Excel cannot access the specified file, which could be due to several reasons, such as the file path being incorrect or the file being used by another program.

    Here are a few suggestions to troubleshoot the issue:

    1. Check File Path: Ensure that the file path MacroFolderPath + sTmpExcelFile is correct and that the file actually exists at that location. You can add a check in your code to verify if the file exists before attempting to open it.
    2. File Permissions: Make sure that the application has the necessary permissions to access the file. You might need to check the file's properties and ensure that the user running the application has read/write permissions.
    3. File in Use: Confirm that the file is not currently open in another instance of Excel or by another application. If it is, you will need to close it before your macro can access it.
    4. Error Handling: You have a Try-Catch block around the xlWorkBook = xlApp.Workbooks.Open(MacroFolderPath + sTmpExcelFile) line. Consider logging the exception message in the catch block to get more insight into what might be going wrong.
    5. Excel Instance: Ensure that the Excel application instance (xlApp) is properly initialized and not being closed prematurely in your code.

    If you continue to face issues, you may want to simplify the code to isolate the problem or test it with a different file to see if the issue persists.


    References:

    0 comments No comments

  2. Jiachen Li-MSFT 32,961 Reputation points Microsoft Vendor
    2024-11-18T01:47:05.5566667+00:00

    Hi @Sangtani, Payal (CSW) ,

    Here are the potential Issues:

    File Path or Name Issues

    • Ensure that MacroFolderPath and sTmpExcelFile together form a valid file path.
    • Check for typos, invalid characters, or missing path separators (\).
      • Use Path.Combine() to construct paths instead of string concatenation for better reliability: Dim filePath As String = Path.Combine(MacroFolderPath, sTmpExcelFile)

    File Already in Use

    • Ensure no other application or instance of your code has the file open when calling xlApp.Workbooks.Open(). Use FileInfo to check if the file is locked:
    Dim fi As New FileInfo(filePath)
    If fi.IsReadOnly OrElse IsFileLocked(fi) Then
        Throw New IOException("File is currently in use.")
    End If
    

    Permission Issues- Ensure the application has permission to read/write to the directory MacroFolderPath.

    • Run the application as an administrator or ensure the directory permissions are adequate.
    • Use DirectoryInfo and FileInfo to verify access:
    Dim di As New DirectoryInfo(MacroFolderPath)
    If Not di.Exists Then Throw New DirectoryNotFoundException("Directory does not exist.")
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.