使用VB.Net从文件读取,编辑单元格,最后保存

时间:2013-11-16 06:55:22

标签: vb.net save excel-2007 savechanges

    Public Function SetInfo(ByRef place As String, ByRef name As String) As Boolean
    Dim Completed As Boolean = False
    Dim MyExcel As New Excel.Application

    Dim myworkbook As New Excel.Workbook

    myworkbook = MyExcel.Workbooks.Open(place)

    MyExcel.Workbooks.Open(place)


    Dim x As Integer
    Dim y As Integer
    Dim finish As Boolean = False

    MyExcel.Sheets("Sheet1").activate()
    MyExcel.Range("B1").Activate()



    Do
        If MyExcel.ActiveCell.Value = name Then
            Exit Do

        Else

            MyExcel.ActiveCell.Offset(0, 1).Activate()

        End If
    Loop


    Do
        If MyExcel.ActiveCell.Text = "" Then

            MyExcel.ActiveCell.Value = "attended"
            MsgBox("Wrote.")
            Exit Do
        Else
            MyExcel.ActiveCell.Offset(1, 0).Activate()
        End If
    Loop

    myworkbook.Save()
    MyExcel.Workbooks.Close()

    MyExcel = Nothing
    Return finish
End Function

我将解释这段代码。

从Cell B1开始,每当单元格不包含我想要的内容时,激活单元格就会向右移动。

如果单元格是我想要的,它会一直下降,直到程序找到空白区域。

在这个过程中,没有问题。

在保存过程中,会出现问题。

如果我删除这些部分

    Dim myworkbook As New Excel.Workbook

    myworkbook = MyExcel.Workbooks.Open(place)

    myworkbook.Save()

“有些事情发生了变化,你会救它吗?”这个Excel消息框出来了。

我不想看到消息框,我想将它保存在我的程序中。

我该怎么办?

PS.Sry因为我的英语不好。

1 个答案:

答案 0 :(得分:0)

Application.DisplayAlerts = False

 myworkbook.Save()

Application.DisplayAlerts = True

或者您可以使用.saveAs() msdn:http://msdn.microsoft.com/de-de/library/microsoft.office.tools.excel.workbook.saveas(v=vs.80).aspx

请参阅:Saveas issue Overwrite existing file ( Excel VBA)

 Sub Sample()
            Dim fName As Object

            '~~> Offer user to Save the file at a particular location
            fName = Application.GetSaveAsFilename

            '~~> Check if it is a valid entry
            If fName <> False Then
                '~~> Check before hand if the file exists
                If Not Dir(fName) <> "" Then
                    '~~> If not then save it
                    ActiveWorkbook.SaveAs Filename:=fName
                Else
                    '~~> Trap the error and ignore it
                    On Error Resume Next
                    If Err.Number = 1004 Then
                        On Error GoTo 0
                    Else '<~~ If user presses Save
                        ActiveWorkbook.SaveAs(Filename:=fName, _
                        FileFormat:=xlWorkbook, _
                        ConflictResolution:=xlLocalSessionChanges)
                    End If
                End If
            End If
        End Sub