在excel文件中查找并替换,然后用Excel应用程序打开它。

问题描述 投票:0回答:1

我想在一个xls文件中进行替换,然后用Excel打开它。

Imports Microsoft.Office.Interop.Excel
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        OpenFileDialog1.ShowDialog()
    End Sub

    Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
        Dim strFileName As String

        OpenFileDialog1.Title = "Apri file TimeSheet"
        OpenFileDialog1.InitialDirectory = "c:"
        OpenFileDialog1.Filter = "File Excel (*.xls)|*.xls|All files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True

        If OpenFileDialog1.FileName.Length > 0 Then
            strFileName = OpenFileDialog1.FileName
            Dim xlapp As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application()
            Dim wb As Microsoft.Office.Interop.Excel.Workbook = Nothing
            wb = xlapp.Workbooks.Open(strFileName.ToString())
            wb.Worksheets(1).Cells.Replace(".", ",")
            wb.Save()
            wb.Close()
            Threading.Thread.Sleep(500)
            Process.Start("EXCEL.EXE", strFileName)
            End
        End If
    End Sub
End Class

但是process.start失败*,因为文件似乎被移动了,即使路径和文件名相同。如何在运行时(指没有用户干预)解决这个问题?

*意味着Excel应用启动了,但无法打开文件,并抛出一个关于 "无法打开文件,可能是文件被移动了,或者是无法访问 "的错误。

excel vb.net openfiledialog find-replace
1个回答
1
投票

我替换了

Process.Start("EXCEL.EXE", strFileName)

Process.Start("EXCEL.EXE", """" & strFileName & """")

第一次失败,因为文件名中含有空格。

© www.soinside.com 2019 - 2024. All rights reserved.