iT邦幫忙

1

vba尋找下一個空白儲存格

https://ithelp.ithome.com.tw/upload/images/20210218/20135236f2UXWYPThv.png
想請問一下:
假如我K3儲存格輸入數量3後按enter,想寫VBA程式自動判斷:
B2儲存格有資料就跳到E2;那如果E2有資料就自動跳到B3,以此類推。
(B2有資料就跳E2,E2有資料就跳B3,B3有資料就跳E3,直到無資料的空白儲存格)
PS:K欄輸入數量後,都會自動跑到無空白的儲存格。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
japhenchen
iT邦超人 1 級 ‧ 2021-02-18 13:36:59
最佳解答

1、開新EXCEL,並把你的表格布置好
2、按下 ALT + F11 進入VBA 編輯功能裡
3、在左側專案窗格裡找到"工作表1",在上面按滑鼠右鍵→檢視程式碼
https://ithelp.ithome.com.tw/upload/images/20210218/20117954uqVcyDjXmc.jpg

4、右邊會出現程式碼窗格,內容是空的,把以下的程式碼貼上即可

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim KeyCells As Range
  Set KeyCells = Range("K3")
  If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
  ' 在 K3 格發生變化時才執行以下事件
    lastusedrow = ActiveSheet.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlFormulas).Row + 1
    For i = 1 To lastusedrow
        If IsEmpty(ActiveSheet.Cells(i, 2)) Then
            '如果 Bn列為空
            ActiveSheet.Cells(i, 2).Value = KeyCells.Value
            Exit For
        End If
        
        If IsEmpty(ActiveSheet.Cells(i, 5)) Then
            '如果 En列為空
            ActiveSheet.Cells(i, 5).Value = KeyCells.Value
            Exit For
        End If
    Next
  End If
End Sub

5、如果解決你的問題,請給分,不然...../images/emoticon/emoticon59.gif

看更多先前的回應...收起先前的回應...

執行結果.......
https://ithelp.ithome.com.tw/upload/images/20210218/20117954TF71gTrKF8.jpg

Neish iT邦研究生 1 級 ‧ 2021-02-18 14:10:10 檢舉

路過看到japhenchen分享
第一次看到Intersect的用法 還去Google一下
感覺還蠻實用的

kent2000 iT邦新手 5 級 ‧ 2021-02-19 00:16:05 檢舉

不是要把"值"複製過去,是綠色的編輯框要跳過去,這樣有辦法嗎?

編輯框?所以K3不是編輯格咯?

        If IsEmpty(ActiveSheet.Cells(i, 5)) Then
            '如果 En列為空
            ActiveSheet.Cells(i, 5).Select '跳到這格E列的空白格
            Exit For
        End If
1
海綿寶寶
iT邦大神 1 級 ‧ 2021-02-18 14:21:26
'跳下一個「空白」的儲存格
Sub BEJump()
    Range("B1024").End(xlUp).Offset(1, 0).Select
    If IsEmpty(ActiveCell.Offset(-1, 3)) Then
        ActiveCell.Offset(-1, 3).Select
    End If
End Sub
'只有修改 K欄 的值時才會跳
Private Sub Worksheet_Change(ByVal Target As Range)
    If Left(Target.Address, 2) = "$K" Then
        Call Module1.BEJump
    End If
End Sub

我要發表回答

立即登入回答