試試看:
Private Sub CommandButton1_Click()
Dim Lst As Integer, R As Integer
Dim Rng As Range, MH
Dim sh As Worksheet
Set sh = Sheets("主頁")
Lst = sh.[A65536].End(xlUp).Row '取得"主頁"欄A 最下面非空白格的列號
R = 1
Set Rng = sh.Range("A2:A" & Lst)
MH = Application.Match(TextBox1.Value, Rng, 0)
If Not Application.IsNumber(MH) Then GoTo 101: '如果TextBox1的資料不在A欄中→新增
R = R + MH
If Range("B" & R) = TextBox2.Value Then '否則,比對TextBox2與B欄
' If Range("C" & MH) <> "" Then GoTo 101: '??如果C欄非空白格→要不要新增??
Range("C" & R) = TextBox2.Value '否則C欄為空白格→C欄=B欄
Exit Sub '即 司機人員(2)=司機人員(1)
End If
'重覆上列動作, 直到 R+1>Lst
Do
Set Rng = sh.Range("A" & R + 1 & ":A" & Lst)
MH = Application.Match(TextBox1.Value, Rng, 0)
If Not Application.IsNumber(MH) Then GoTo 101:
R = R + MH
If Range("B" & R) = TextBox2.Value Then
Range("C" & R) = TextBox2.Value
Exit Sub
End If
Loop Until R + 1 > Lst
101:
'新增一列資料
Range("A" & Lst + 1) = TextBox1.Value
Range("B" & Lst + 1) = TextBox2.Value
End Sub作者: man65boy 時間: 2016-3-5 23:15
Private Sub CommandButton1_Click()
Dim xNo$, xName$, xR As Range
xNo = TextBox1: xName = TextBox2
For Each xR In Range([A2], [A65536].End(xlUp))
If xR = xNo And xR(1, 2) = xName And xR(1, 3) = "" Then
xR(1, 3) = xName: xR(1, 5) = Now: Exit Sub
End If
Next
[A65536].End(xlUp)(2).Resize(1, 4) = Array(xNo, xName, "", Now)
End Sub
1.最好在前面加入檢錯:
〔編號〕限制〔英大寫〕+數字12碼
If Not xNo Like "[A-Z]############" Then MsgBox "編號錯誤或未輸入!": Exit Sub
If xName = "" Then MsgBox "司機名未輸入!": Exit Sub
2.防錯是VBA最重要的,建議〔出車〕與〔回車〕分別兩個按鈕執行,
否則若編號或姓名輸入一字之差,本來是回車變成出車!作者: 准提部林 時間: 2016-3-6 11:57
〔出車〕〔回車〕分別處理:
Dim xChk&
Private Sub CommandButton1_Click()
xChk = 1: Call 記錄
End Sub
Private Sub CommandButton2_Click()
xChk = 2: Call 記錄
End Sub
Sub 記錄()
Dim xNo$, xName$, xR As Range
xNo = TextBox1: xName = TextBox2
If Not xNo Like "[A-Z]############" Then MsgBox "編號錯誤或未輸入!": Exit Sub
If xName = "" Then MsgBox "司機名未輸入!": Exit Sub
For Each xR In Range([A2], [A65536].End(xlUp))
If xR = xNo And xR(1, 2) = xName And xR(1, 3) = "" Then
If xChk = 1 Then MsgBox "本車次尚未回車,請確認!": Exit Sub
If xChk = 2 Then xR(1, 3) = xName: xR(1, 5) = Now: Exit Sub
End If
Next
If xChk = 1 Then [A65536].End(xlUp)(2).Resize(1, 4) = Array(xNo, xName, "", Now): Exit Sub