嗨,我嘗試創建一個代碼,以便用戶無法在表中插入相同的 id,所以我創建了一個插入按鈕,在他實際插入某些東西之前對其進行驗證,但由于某種原因它不起作用,請幫助我(我是新手VBA):
這是我的代碼:
Sub Insert()
'
' insert Macro
'
Dim row As Double, search As String
row = 5
search = ""
Do
row = row 1
If Sheet1.Cells(17, 9).Value = Data.Cells(row, 1).Value Then GoTo Error
If Sheet1.Cells(17, 9).Value <> Data.Cells(row, 1).Value Then GoTo Insert
Exit Do
Loop Until Data.Cells(row, 1).Value = ""
Error:
search = "Ok"
MsgBox "Id already exists", vbExclamation,"Error"
Exit Sub
Insert:
If IsEmpty(Range("I17")) Or IsEmpty(Range("D11")) and search ="" Then
MsgBox "all the fields must be filled", vbExclamation
Else:
' heres the code to insert values from sheet1 to sheet2
End If
Exit Sub
由于某種原因,它沒有回圈它唯一驗證是否在另一張表(資料)的表的第一行中找到的值,即第 6 行。sheet1 中的單元格和資料中的列都轉換為數字格式(完全正確相同)。
這是用戶插入的 ID,我試圖驗證 ID 是 I17 單元格(作業表名稱是表格):

Ps:如果您需要更多資訊,請告訴我
如果值匹配(資料表),這是我試圖查看的欄位:

uj5u.com熱心網友回復:
因為我不知道你到底想做什么,這是讓你開始的最簡單的方法。
Sub Insert()
'
' insert Macro
'
Dim row As Double, search As String
row = 5
search = ""
Do
row = row 1
If Sheet1.Cells(17, 9).Value = Data.Cells(row, 1).Value Then
'What to do if the value matched Goes Here
MsgBox "Id already exists on Data in Row: " & row, vbExclamation,"Error"
Exit Sub 'if you want to exit when the value was found
Else
'You want to leave this empty and do what you want to do after the loop is done
'and a match was not found
End If
Loop Until Data.Cells(row, 1).Value = ""
'End of the loop.
'If the Sub gets to this point it means that the Value was not found at all after looping all the data.
'Enter below what to do if the value was not found
Data.Cells(row, 1).Value = Sheet1.Cells(17, 9).Value
Data.Cells(row, 2).Value = Sheet1.Cells(17, 12).Value 'Which Column has the name? I guessed 12
Exit Sub
我猜這會起作用,但是這是尋找值的一種非常糟糕的方法,相反,您可以使用Data.Columns("A:A").Find(What:=Sheet1.Cells(17,9).Value)并且不必回圈,我建議您在嘗試之前對該方法進行一些閱讀/谷歌搜索方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492084.html
下一篇:獲取單擊單元格的值
