Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 循环范围选择_Excel_Vba - Fatal编程技术网

Excel 循环范围选择

Excel 循环范围选择,excel,vba,Excel,Vba,有没有一种简单的方法可以创建一个不是长方体而是以ActiveCell为中心的圆的范围?我可以一次定义一行,但我希望这里有人知道一个更优雅的解决方案 更新: 多亏了JvDV的帮助,我决定采用以下解决方案: Sub revealMap(playerLocation As Range, sightDistance As Integer) Dim search As Range, cl As Range Dim stcol As Integer, strow As Integer Dim endrow

有没有一种简单的方法可以创建一个不是长方体而是以ActiveCell为中心的圆的范围?我可以一次定义一行,但我希望这里有人知道一个更优雅的解决方案

更新:

多亏了JvDV的帮助,我决定采用以下解决方案:

Sub revealMap(playerLocation As Range, sightDistance As Integer)
Dim search As Range, cl As Range
Dim stcol As Integer, strow As Integer
Dim endrow As Integer: endrow = 1 + sightDistance * 2
Dim endcol As Integer: endcol = 1 + sightDistance * 2

If playerLocation.row - sightDistance < 0 Then
    strow = 1
    endrow = endrow - playerLocation.row
Else
    strow = playerLocation.row - sightDistance
End If
If playerLocation.Column - sightDistance < 0 Then
    stcol = 1
    endcol = endcol - playerLocation.col
Else
    stcol = playerLocation.Column - sightDistance
End If
Set search = ActiveSheet.Cells(strow, stcol)

For Each cl In search.Resize(endrow, endcol)
    If (Sqr((Abs(cl.row - playerLocation.row)) ^ 2 + (Abs(cl.Column - playerLocation.Column)) ^ 2) <= sightDistance) And (cl.Interior.ColorIndex = 1) Then
        Worksheets("Map Ref").Cells(cl.row, cl.Column).Copy (Worksheets("World Map").Cells(cl.row, cl.Column))
    End If
Next cl
End Sub

这样的办法应该行得通。这只是一颗迷你钻石,但你明白了

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

'select all the cells surrounding the current cell
Application.EnableEvents = False

strRange = Target.Offset(0, 1).Address & "," & Target.Offset(1).Address & "," & Target.Offset(0, -1).Address & "," & _
            Target.Offset(-1).Address & "," & Target.Address

Range(strRange).Select
Target.Activate
Application.EnableEvents = True

End Sub

请确保将该代码放在ThisWorkbook对象中。

只是为了好玩。根据@BigBen,您需要某种类型的逻辑。例如,钻石案的一个样本:

Sub Test()

Dim rng1 As Range, rng2 As Range: Set rng1 = ActiveCell

For Each cl In ActiveCell.Offset(-3, -3).Resize(7, 7)
    If Abs(cl.Row - rng1.Row) + Abs(cl.Column - rng1.Column) <= 3 Then
        If Not rng2 Is Nothing Then
            Set rng2 = Union(rng2, cl)
        Else
            Set rng2 = Union(rng1, cl)
        End If
        Debug.Print rng2.Address
    End If
Next cl

rng2.Select

End Sub
就像@Galimi一样,我没有考虑边缘案例


祝你好运。

这不是一个简单的方法,但是你可以创建一个算法来实现这一点。没有考虑上面的边。这很好。我想我会尝试一种更为毕达哥拉斯式的方法,但谢谢你的启发。