qq_34300825
2019-05-05 15:06
采纳率: 100%
浏览 813

VB.net调用Excel两个问题

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim i As Integer
        xlApp = CreateObject("Excel.Application") '创建EXCEL应用类
        xlApp.Visible = True '设置EXCEL可见
        xlBook = xlApp.Workbooks.Open("E:\bb.xlsm") '打开EXCEL工作簿
        xlSheet = xlBook.Worksheets(1) '打开EXCEL工作表
        xlSheet.Activate() '激活工作表xlSheet.Activate()
        i = 1
        Do Until xlSheet.Cells(i, 1) = ""
            i = i + 1
        Loop
        xlSheet.Cells(i, 1) = TextBox1.Text '给单元格1行驶列赋值xlSheet.Cells(1, 1) & 
        xlBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoOpen) '运行EXCEL中的启动宏
        xlBook.Save()
        xlBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoClose) '执行EXCEL关闭宏
        xlBook.Close(True) '关闭EXCEL工作簿
        xlApp.Save()
        xlApp.Quit() '关闭EXCEL
        xlSheet = Nothing
        xlBook = Nothing
        xlApp = Nothing '释放EXCEL对象
        MsgBox("保存成功")
    End Sub!
        [图片说明](https://img-ask.csdn.net/upload/201905/05/1557039717_488488.png)![图片说明](https://img-ask.csdn.net/upload/201905/05/1557039769_163946.png)


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • qq_34300825 2019-05-07 14:01
    已采纳

    换了一种方法,点一次保存对i+1,删除了xlApp.Save()EXCEL会自动保存

    Public a As Integer = 1
    
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            a = a + 1
            xlApp = CreateObject("Excel.Application") '创建EXCEL应用类
            xlApp.Visible = True '设置EXCEL可见
            xlBook = xlApp.Workbooks.Open("E:\会议人员名单.xlsm") '打开EXCEL工作簿
            xlSheet = xlBook.Worksheets(1) '打开EXCEL工作表
            xlSheet.Activate() '激活工作表
            xlSheet.Cells(a, 1) = TextBox1.Text '给单元格1行驶列赋值
            xlSheet.Cells(a, 2) = TextBox2.Text
            xlSheet.Cells(a, 3) = TextBox3.Text
            xlSheet.Cells(a, 4) = TextBox4.Text
            xlSheet.Cells(a, 5) = TextBox5.Text
            xlBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoOpen) '运行EXCEL中的启动宏
            xlBook.Save()
            xlBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoClose) '执行EXCEL关闭宏
            xlBook.Close(True) '关闭EXCEL工作簿
            xlApp.Quit() '关闭EXCEL
            xlSheet = Nothing
            xlBook = Nothing
            xlApp = Nothing '释放EXCEL对象
            MsgBox("保存成功")
        End Sub
    
    已采纳该答案
    打赏 评论
  • abc19000101 2019-05-05 18:29

    建议用aspose.cells,去掉对office的依赖

    打赏 评论
  • weixin_50391995 2021-05-25 11:31

    我想问一下不添加Excel引用,直接用代码不行吗

    打赏 评论

相关推荐 更多相似问题