Macro doesn't work if I add a second sheet in calc

I’m trying to make this macro working to clear all data fields in my calc file.

Sub Erase_Fields
    oSheet = ThisComponent.getSheets()
    oObj1 = oSheet.getByIndex(0)
    oForm = oObj1.Drawpage.Forms.getByName("Data")
    oField1 = oForm.getByName("data1")
    oField1.Text = " "
    oField1.Text = ""
    oField2 = oForm.getByName("data2")
    oField2.Text = " "
    oField2.Text = ""
    oField3 = oForm.getByName("data3")
    oField3.Text = " "
    oField3.Text = ""
end sub

It works (thanks to @Ratslinger here but it seems to work just with one sheet. If I add a second sheet, it gives me back an error. I need to clear only the date fields on the first sheet, but I need to add other sheets to the file.Date field multiple.ods

Hello,

You are better off using the second method mentioned in the original linked answer. It will keep the data erased and will not refresh by simply changing sheets. Here is the code needed even when it is not the first sheet (uses sheet name):

Sub Erase_Fields
    oSheet = ThisComponent.getSheets()
    oObj1 = oSheet.getByName("Foglio1")
    oForm = oObj1.Drawpage.Forms.getByName("Data")
    DocCtl = ThisComponent.getCurrentController()
    oField = oForm.getByName("data1")
'Get VIEW'
    CtlView = DocCtl.GetControl(oField)
    CtlView.setEmpty()    
    oField = oForm.getByName("data2")
'Get VIEW'
    CtlView = DocCtl.GetControl(oField)
    CtlView.setEmpty()    
    oField = oForm.getByName("data3")
'Get VIEW'
    CtlView = DocCtl.GetControl(oField)
    CtlView.setEmpty()    
end sub

Thank you. This is the perfect, elegant solution. It works just fine!

Do not add “[SOLVED]” to the title. Instead, mark the answer as accepted. See guidelines for asking.

Done. Thanks for the tip