VBA - Excel,在所选单元格的worksheet.copy()上崩溃有新文本

时间:2013-01-07 19:24:24

标签: vb.net excel-2010

我是VB的新手,在尝试复制工作表时遇到了令人沮丧的崩溃。

调用worksheet.Copy()大部分时间都可以正常工作,但是当用户在单元格中输入文本而未取消选择该单元格或按下输入时,它会崩溃并显示消息“复制工作表类的消息失败”,并出现错误代码-2146827284。任何人都可以告诉我为什么会这样吗?

这是整个sub(当用户单击excel功能区中的按钮时调用)

Friend Sub CheckSheet(ByRef worksheet As Microsoft.Office.Interop.Excel.Worksheet, ByVal testType As List(Of String), ByRef guide As List(Of String), ByRef display As Dictionary(Of String, Boolean), ByRef URL As String)

        'Read the labels and units from the current worksheet
        Dim readings = loadReadings(worksheet, 3, 3, 4)
        If readings Is Nothing Then 'If the readings are not successfully loaded
            Exit Sub
        End If

        'Create a copy of the workbook to be processed to put the results in
        Dim originalFilename As String = Application.ActiveWorkbook.FullName
        Dim using1904system As Boolean = Application.ActiveWorkbook.Date1904

        worksheet.Copy() 'FIXME Crash here if selected cell has newly entered text

        worksheet = Application.ActiveWorkbook.ActiveSheet
        Application.ActiveWorkbook.Date1904 = using1904system 'Make sure the new worksheet uses the same date option

        'Get requests from worksheet
        Dim cellMap = New Dictionary(Of String, Range)
        Dim allRequests = getRequests(worksheet, readings, cellMap, 5, testType, guidelines, 1, 2, 3)

        'Gets the results from the server and outputs them to a new Excel workbook
        Dim success = processResults(allRequests, URL, worksheet, display, cellMap, 5, originalFilename, testType, guidelines)
        If Not success Then
            Exit Sub
        End If

        'Set focus to the checked worksheet
        worksheet.Activate()

    End Sub

修改

我尝试通过选择不同的单元格来编程取消选择单元格,例如:

worksheet.Range("A1").Activate()

但这似乎没有任何影响(崩溃仍然发生)。我的添加仅在用户明确指示时调用复制方法,因此,如果用户已停止在单元格中输入文本并单击按钮运行我的添加,这似乎是一个非常安全的假设,它们是完成在框中输入文本。

1 个答案:

答案 0 :(得分:-1)

此问题的原因是Excel等待User-Excel成为以用户为中心的应用程序,所有操作都必须等到用户完成数据输入。 我认为这种情况很有用,因为此时单元格的文本在技术上是未定义的,因此如果用户编辑单元格,按下按钮然后完成输入数据,您将产生克拉普结果 - 您将使用旧数据,这没用。

我见过这个帖子:How to detect a cell is selected for editing in excel 这应该有所帮助 否则,您可以将代码包装在try ... catch块中并解析返回的错误代码。如果是你的错误代码显示一条消息,如“ooops请完成编辑文本框”。但我认为事件会更好。