返回列表 上一主題 發帖

[發問] 輸入[編號]自動顯示[姓名],查無資料時,如何清空儲存格

[發問] 輸入[編號]自動顯示[姓名],查無資料時,如何清空儲存格

本帖最後由 dou10801 於 2023-2-7 22:43 編輯

輸入[編號]自動顯示[姓名],查無資料時,如何清空儲存格,感恩.


Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xF As Range
    Application.ScreenUpdating = False
    If Target.Count > 2 Or Target.Column <> 2 Then End   
     Set xF = [摘要!a:a].Find(Target.Value, Lookat:=xlWhole)
     If xF Is Nothing Then
        MsgBox "找不到!"
        工作表2.Cells(Target.Row, 3) = ""
        '工作表2.Cells(Target.Row, 2) = ""  '這行無作用
        Exit Sub
     Else
        m1 = xF(2, 1)
        工作表4.Cells(m1, 2).Copy 工作表2.Cells(Target.Row, 3)
     End If
    Application.ScreenUpdating = True
     Set xF = Nothing
End Sub

銷售統計22.rar (17.74 KB)

杜小平

回復 1# dou10801


    謝謝前輩發表此主題與範例
後學試理解需求,建議如下:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xF As Range
    Application.ScreenUpdating = False
    If Target.Count > 2 Or Target.Column <> 2 Then End
     Application.EnableEvents = False '讓觸發失效才不會連續觸發
     Set xF = [摘要!a:a].Find(Target.Value, Lookat:=xlWhole)
     If xF Is Nothing Then
        MsgBox "找不到!"
        工作表2.Cells(Target.Row, 3) = ""
        工作表2.Cells(Target.Row, 2) = ""
        'Exit Sub
     Else
        m1 = xF(2, 1)
        工作表4.Cells(m1, 2).Copy 工作表2.Cells(Target.Row, 3)
     End If
    Application.ScreenUpdating = True
     Set xF = Nothing
     Application.EnableEvents = True '最後才讓觸發恢復
End Sub
用行動裝置瀏覽論壇學習很方便,謝謝論壇經營團隊
請大家一起上論壇來交流

TOP

回復 2# Andy2483 感恩,VBA還有很多小細節要學習.
杜小平

TOP

回復 1# dou10801


    Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Column <> 2 Then Exit Sub
If Target.Row = 1 Then Exit Sub
If IsNumeric(Target.Value) = fasle Then Exit Sub
Set cn = CreateObject("adodb.connection")
Select Case Application.Version
Case Is < 12: cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0; Data Source=" & ThisWorkbook.FullName
Case Else: cn.Open = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0; Data Source=" & ThisWorkbook.FullName
End Select

Sql = "select count(*) as ct from [摘要$a1:B] where 代號 = '" & Format(Target.Value, "000") & "'"
Set rs = cn.Execute(Sql)
Application.EnableEvents = False
If rs.getrows(, , "ct")(0, 0) = 1 Then  '偵錯時 容易失效
    Set rs = cn.Execute("select * from [摘要$a1:B] where 代號 = '" & Format(Target.Value, "000") & "'")
    Cells(Target.Row, 2).CopyFromRecordset rs '.getrows '(,,array("代號","姓名"))
Else
    Target.Value = ""
End If
Application.EnableEvents = True
cn.Close
Set cn = Nothing
End Sub

TOP

        靜思自在 : 不要隨心所欲,要隨心教育自己。
返回列表 上一主題