在VBA公式中定义和使用名称

好的,我对VBA来说很新,而且遇到了这个障碍。

我想为VBA中的一列date(“date”)定义一个名称,然后在VBA公式中使用该名称。

这里是我在excel中定义名称的地方:

Sub Build_dates(as_of_date As String, curve_source As String) 'Code Range("B14").Select Range(Selection, Selection.End(xlDown)).Select ActiveWorkbook.Names.Add Name:="dates", RefersTo:=Selection.Address 'More Code End Sub 

这里是我希望使用它的子:

 Sub Build_times(interp_count As String, as_of_date As String) Dim First As Range, Last As Range, fillRange As Range Set First = Range("C14") Set Last = Range("B14").End(xlDown).Offset(0, 1) Set fillRange = Range(First.Address & ":" & Last.Address) Select Case interp_count Case "Act/360" First.Formula = "=(dates-$B$14)/360" First.AutoFill Destination:=fillRange Case "Act/365" First.Formula = "=(dates-$B$14)/365" First.AutoFill Destination:=fillRange End Select 'Add name to the time column Range("C14").Select Range(Selection, Selection.End(xlDown)).Select ActiveWorkbook.Names.Add Name:="times", RefersTo:=Selection.Address End Sub 

问题是“times”列中的每个单元格都有#VALUE! 在里面。 我查看了在每个单元上出现的上下文菜单中的“显示计算步骤”选项,看到这个:

 ("$B$14:$B$81"-36526)/360 

其中计算括号内的值为#VALUE!

我定义的名称都不出现在左上angular的下拉菜单中,但是我可以在名称pipe理器中finddate和时间,每个名称都指向

 ="$B$14:$B$81" 

 ="$A$15:$A$81" 

分别。 而我通过手动突出显示范围并在名称框中input名称来定义一个类似的参考

 ='Bootstrap Validation'!$H$13:$H$46 

我应该如何改变我的代码,以便可以使用VBA定义的公式中的命名范围?

为了回答直接的问题,像这样传递一个Range (而不是String )给RefersTo

 ActiveWorkbook.Names.Add Name:="dates", RefersTo:=Selection 

这就是说,你不应该使用Select / Selection的代码。 看到这个答案的一些如何避免这些检查。