簡體   English   中英

更改范圍內的可變行時激活宏

[英]Activate macro on change with variable row in range

我想在范圍更改時激活宏。

下面的代碼工作正常,除了我要在最后一行使用變量( B100當前在哪里)。

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("B1:B100")) Is Nothing Then
        MsgBox "Updating sheets"
        Call Thickborders2

    End If
End Sub

范圍中的B100取決於最后一行中包含文本的位置。

您可以借用工作表技巧,以找到其中包含文本的最后一行。

=MATCH("zzz", B:B)

上面的代碼返回帶有文本值的B列的最后一行。

Private Sub Worksheet_Change(ByVal Target As Range)

    dim m as variant
    m = application.match("zzz", columns("B"))
    if iserror(m) then m = 1

    If Not Intersect(Target, Range("B1").resize(m, 1)) Is Nothing Then

        MsgBox "Updating sheets"
        Call Thickborders2

    End If
End Sub

我強烈建議添加錯誤控制( on error goto <label> )並禁用事件觸發器( application.enableevents = false )。 記住在退出子菜單之前重新啟用事件。

正如我在對OP的評論中所說的那樣,單獨使用Worksheet_Change將不起作用,因為它將基於剛剛輸入的數據來計算最后一個單元格。

這段代碼將在您移動單元格時計算最后一個單元格(我嘗試了Calculate事件,但這是在您添加數據之后發生的,與Change事件一樣,是同樣的問題)。

Option Explicit

Private rLastCell As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Set rLastCell = Cells(Rows.Count, 2).End(xlUp)
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range(Cells(1, 2), rLastCell)) Is Nothing Then
        MsgBox "Updating sheets"
        Call Thickborders2
    End If
End Sub  

前兩行必須在模塊的最上方。

基於Taazar和L42的評論,請嘗試:

Private Sub Worksheet_Change(ByVal Target As Range)
    LastCell = Activesheet.Usedrange.Rows.Count
    If Not Intersect(Target, Range("B1:B" & LastCell)) Is Nothing Then
        MsgBox "Updating sheets"
        Call Thickborders2
    End If
End Sub

Activesheet應替換為您要檢查的工作表名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM