I'm trying to open a file using a function. The same code is working if I call it by a button. The file will open, I can modify it and I can close it without saving. But if I use the same code called by the function the file will not be open. Why? Following the code used with the button and with the function. Might anyone help me? This is only the beginning of what I would need. Detailing, with this function I need to open a CSV file, fix the CSV file, extract a data with a Dlookup and write this data on the cell where I called the function. This works if I call my code by button but not if I call it with a function in a cell
Sub Button1_Click()
Dim path As String
Dim xl As Excel.Application
Dim wk As Excel.Workbook
path = ActiveWorkbook.path & "\Book1.xlsm"
Set xl = Excel.Application
Set wk = xl.Workbooks.Open(path)
xl.Visible = True
wk.Activate
xl.DisplayAlerts = False
Range("B2").Select
Range("B2").Value = "hello world"
wk.Saved = False
wk.Close
Set wk = Nothing
End sub
Public Function aprifile()
Dim path As String
Dim xl As Excel.Application
Dim wk As Excel.Workbook
path = ActiveWorkbook.path & "\Book1.xlsm"
Set xl = Excel.Application
Set wk = xl.Workbooks.Open(path)
xl.Visible = True
wk.Activate
xl.DisplayAlerts = False
Range("B2").Select
Range("B2").Value = "hello world"
wk.Saved = False
wk.Close
Set wk = Nothing
End Function