如何在Worksheet_Change事件期间从目标获取行号?

时间:2019-06-18 03:02:17

标签: excel vba

我有以下代码可检测到单元格值已更改。我想知道该单元格属于哪一行。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.

    Set KeyCells = Range("F2:F20")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
        MsgBox "Last Contact Date " & Target.Address & " has changed."
        Set Row_number = ???????

    End If

End Sub

2 个答案:

答案 0 :(得分:1)

它可以从Target variablerange中提取,您可以从中提取很多信息,包括Row。就您而言,它看起来像这样:

已更新,以防止用户有多于一行的可能性。有关该怎么做的一些建议。

If Target.Rows.Count > 1 Then
    'do nothing

    'or
    MsgBox "You messed up by selecting " & Target.Rows.Count & " rows!!!", _
    vbCritical, "Come on!"

    'or
    Row_Number = Target.Cells(1, 1).Row 'this will return the top row selection


Else
    'when one row
    Row_Number = Target.Row

End If

答案 1 :(得分:1)

from random import uniform
import numpy as np

def new_haversine_np(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)

    """
    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

    dlon = lon2 - lon1[:,None]

    dlat = lat2 - lat1[:,None]

    a = np.sin(dlat/2.0)**2 + np.cos(lat1[:,None]) * np.cos(lat2) * np.sin(dlon/2.0)**2

    c = 2 * np.arcsin(np.sqrt(a))
    km = 6367 * c
    return km

lon1 = [uniform(-180,180) for n in range(6)]
lat1 = [uniform(-90, 90) for n in range(6)]
lon2 = [uniform(-180,180) for n in range(4)]
lat2 = [uniform(-90, 90) for n in range(4)]

new = new_haversine_np(lon1, lat1, lon2, lat2)

for i in range(6):
    for j in range(4):
        print(i,j,round(new[i,j],2))