简体   繁体   English

VBA UDF在测试中有效,但在excel中使用时不起作用

[英]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 cday指的是excel中带有日期的单元格,例如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 它匹配并找到数据集的行和列,并将其输入到数组(dpricebase)中,该数组我已经通过子程序预先用数据填充

I wrote a small sub that evokes it and it works. 我写了一个小子使它生效,它起作用了。 I try to use it directly at the excel and it does not! 我尝试直接在excel上使用它,但事实并非如此!

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: UDF存在几个问题:

  • lastday lastrow and totalcomm are not defined anywhere lastday lastrow和totalcomm在任何地方都没有定义
  • You cannot use sheet.activate or window.activate inside a UDF 您不能在UDF中使用sheet.activate或window.activate
  • you should use Option Explicit 您应该使用Option Explicit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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