为什么我在 Excel Vba 中的这个函数的 for 循环中得到了额外的选择?

Why am I getting an extra selection in my for loop from this function in Excel Vba?

我正在尝试调试以下函数,当它在它上面列出的子主函数中使用时。

澄清函数参数的用途 15 是间隔和 4 是范围行的起始位置, 64 是结束范围行的地方, 3 是范围开始的列 3 是范围结束的列。

问题出在第一个参数 xInterval 上,当它选择这个间隔时,我在第二个参数之前得到了一个额外的选择。例如 运行 此代码选择 (C4, C18, C19, C34, C49, C64) 我不确定 C18 的来源并且不想要它。欢迎任何建议。谢谢!

Sub Main()

     Dim rng As Range
     Set rng = Every_Fiffteen_min(15, 4, 64, 3, 3)

     End Sub

Function Every_Fiffteen_min(xInterval As Integer, row_start As Long, row_end As Long, Colu_start As Integer, Colu_end As Integer) As Range

' Input an interval defined by xInterval that will set the interval of rows to select.
' Using an input for the range row start, row end, column start and column end in numeric values not alpha.
' I have additional functions that will be used to calculate the row start, end, column start and column end, which is why I need these.

Dim CustomRange As Range 'Inputrng
Dim SelectRow As Range ' OutRng
Dim rng As Range
Dim i As Integer

With Sheets("Data Import")
    
    Set CustomRange = .Range(Cells(row_start, Colu_start), Cells(row_end, Colu_end))
    Set SelectRow = CustomRange.Rows(xInterval)

    For i = 1 To CustomRange.Rows.Count Step xInterval 
        Set rng = CustomRange.Cells(i, 1)
        If SelectRow Is Nothing Then
            Set SelectRow = rng
        Else
            Set SelectRow = Union(SelectRow, CustomRange.Rows(i))
        End If
    Next i

Application.Goto SelectRow
End With

End Function

因为你的台词,额外的射程即将到来Set SelectRow = CustomRange.Rows(xInterval)

您已经从 row_start 循环到 row_end。因此所有指定的范围都将添加到 SelectRow。但是你也有循环顶部的那条线,它将不需要的范围添加到 SelectRow.

如果删除此行,问题将会得到解决。但是在第一个循环中,您将执行 Set SelectRow = rng 而不是 Set SelectRow = Union(SelectRow, CustomRange.Rows(i))。这将再次更改输出范围,根据您提供的描述,这似乎不符合您想要的输出。

要修复所有问题,还要将 Set rng = CustomRange.Cells(i, 1) 行更改为 Set rng = CustomRange.Rows(i)