简体   繁体   中英

VBA UDF works at test but not when used in excel

I'm getting desperate with this!

I have built the function below. The cday refers to a cell in excel with a date, like 01/01/2017

it matches and finds the row and column of a dataset and enters it to an array (dpricebase) which i have filled beforehand with data through a sub

I wrote a small sub that evokes it and it works. I try to use it directly at the excel and it does not!

Pls help!

thank you!

Function findprice (cday, commno)

cday = DateValue(cday)

price1 = 0

If cday > lastday Then ‘last day is a date xx/xx/xxxx at a cell in the excel
    price1 = 0
    GoTo result
End If

Windows("m.xls").Activate
Sheets("Daily").Activate

‘find the matching row
For x = 5 To lastrow
    If DateValue(Cells(x, 2)) = cday Then
        datarow = Cells(x, 2).Row - 5
        GoTo Continue1
    End If
Next x

MsgBox "No data for " & cday & " for " & commno

Continue1:

'find the matching column 
For y = 3 To totalcomm
    If Cells(2, y) = commno Then
        datacol = Cells(2, y).Column - 3
        GoTo Continue2
    End If
Next y

MsgBox "No Daily data for No." & commno

Continue2:

price1 = dpricebase(datarow, datacol)
GoTo result

result:
findprice = price1 
End Function

There are several problems with your UDF:

  • lastday lastrow and totalcomm are not defined anywhere
  • You cannot use sheet.activate or window.activate inside a UDF
  • you should use Option Explicit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM