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

Jac*_*son 0 excel vba excel-vba

好吧,我对VBA很新,我遇到了这个障碍.

我想在VBA中为日期列("日期")定义名称,然后在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
Run Code Online (Sandbox Code Playgroud)

这是我想用它的子:

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
Run Code Online (Sandbox Code Playgroud)

问题是"时间"列中的每个单元格都有#VALUE!在里面.我查看了每个单元格上显示的上下文菜单中的"显示计算步骤"选项,并看到了:

("$B$14:$B$81"-36526)/360
Run Code Online (Sandbox Code Playgroud)

它将带括号的值计算为#VALUE!

我定义的名称都没有出现在左上角的下拉名称菜单中,但我可以在名称管理器中找到日期和时间,每个名称都指向

="$B$14:$B$81"
Run Code Online (Sandbox Code Playgroud)

="$A$15:$A$81"
Run Code Online (Sandbox Code Playgroud)

分别.我通过手动突出显示一个范围并在名称框中键入名称来定义一个产生类似的引用

='Bootstrap Validation'!$H$13:$H$46
Run Code Online (Sandbox Code Playgroud)

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

chr*_*sen 5

要回答直接问题,请将Range(不是a String)传递给RefersTo,就像这样

ActiveWorkbook.Names.Add Name:="dates", RefersTo:=Selection
Run Code Online (Sandbox Code Playgroud)

也就是说,你不应该使用Select/ Selection代码这样的代码.有关如何避免这些问题的一些考试,请参阅此答案.