vba script hangs at Workbook.Close

前端 未结 2 1969
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-18 09:26

I am trying to write a hello world application in Visual Basic for Applications, namely, to modify a cell in an Excel sheet. Here it is:

Sub hello()

    Dim         


        
相关标签:
2条回答
  • 2021-01-18 09:31

    It should be

    Workbooks.Close
    

    I also think that "Workbook" is a reserved word and you should use something like "wb" instead.

    Dim wb As Workbook
    
    0 讨论(0)
  • 2021-01-18 09:34

    The problem is that you are not giving Excel enough time to finish it's operations. Usually a DoEvents will solve the problem. Also to avoid confusion, you might want to name your variable as `wbk' instead of 'Workbook'

    Sub hello()
        Dim obj As Object, wbk As Object
    
        Set obj = CreateObject("Excel.Application")
        Set wbk = obj.Workbooks.Open("C:\Users\gbuday\Desktop\Oktatás\Excel\start.xlsx")
    
        wbk.Worksheets("Munka1").Range("B3") = "Hello World!"
    
        DoEvents
    
        '~~> Change True to False if you do not want to save
        wbk.Close SaveChanges:=True
    
        Set wbk = Nothing: Set obj = Nothing
    End Sub
    
    0 讨论(0)
提交回复
热议问题