循环遍历命名范围excel vba时如何引用特定单元格

时间:2017-08-02 12:16:39

标签: excel vba excel-vba named-ranges

我有一些工作正常的代码,但我最近完全重写了电子表格以使用命名范围。

我现在正在努力重写代码以引用命名范围而不是绝对引用。 (我认为这是术语!?)

File_ref范围占用单元格A13:A104 Already_Input?范围占据细胞B13:B104

我在Windows上使用Excel 2013

有效的代码

Sub test()
Set mybook = Excel.ActiveWorkbook
Set entrysheet = mybook.Sheets("Entry")

Dim RangeStart As Integer
RangeStart = Range("File_ref").Cells(1).Row

Dim RangeLength As Integer
RangeLength = Range("File_Ref").Count

Dim i As Long
Dim j As Long
Dim m As Long

j = 0
m = 0

For i = RangeStart To RangeLength + RangeStart

        If IsEmpty(entrysheet.Range("A" & i)) Then 'it's this bit I cannot get to refer to named range

        j = j + 1

        ElseIf entrysheet.Range("B" & i) = "yes" Then

        m = m + 1

        End If

Next i
End Sub

我尝试过的代码,但不起作用:

Sub test()
Set mybook = Excel.ActiveWorkbook
Set entrysheet = mybook.Sheets("Entry")

Dim RangeStart As Integer
RangeStart = Range("File_ref").Cells(1).Row

Dim RangeLength As Integer
RangeLength = Range("File_Ref").Count

Dim i As Long
Dim j As Long
Dim m As Long

j = 0
m = 0

For i = RangeStart To RangeLength + RangeStart

        If IsEmpty(entrysheet.Range("File_ref").Cells(i)) Then

        j = j + 1

        ElseIf entrysheet.Range("Already_Input?").Cells(i) = "yes" Then

        m = m + 1

        End If

Next i
End Sub

2 个答案:

答案 0 :(得分:0)

您可以尝试以下代码

Sub test()
Set mybook = Excel.ActiveWorkbook
Set entrysheet = mybook.Sheets("Entry")

File_ref = "A1:A10"  ''Added new
Already_Input = "B1:B10" ''Added new
Dim RangeStart As Integer
RangeStart = Range(File_ref).Cells(1).Row

Dim RangeLength As Integer
RangeLength = Range(File_ref).Count

Dim i As Long
Dim j As Long
Dim m As Long

j = 0
m = 0

For i = RangeStart To RangeLength + RangeStart

        If IsEmpty(entrysheet.Range(File_ref).Cells(i)) Then

        j = j + 1

        ElseIf entrysheet.Range(Already_Input).Cells(i) = "yes" Then

        m = m + 1

        End If

 Next i
End Sub

答案 1 :(得分:0)

我弄清楚问题是什么,我误解了我要求代码评估的范围,并且它遗漏了我为测试它而输入的所有样本条目。