這是我在這里的第一個問題,我仍然是一個業余愛好者,但我正在嘗試使用 VBA 完成以下任務:
注意:我沒有自己撰寫的任何現有代碼。我嘗試將幾個代碼混合在一起,我發現它們做了一些類似的事情,但最終我沒有任何作業。
我有一個Sheet1 A列中所有用戶的串列,以及一個Sheet2 A 列中特定用戶的串列。
我需要用我的代碼完成以下操作:
- 回圈遍歷 Sheet1 中的每一行,A 列
- 檢查值是否存在于 Sheet2 的 A 列串列中
- 如果值不存在,則洗掉該行并繼續下一步
所以最后我只想將那些值保留在那個 sheet1 列 A 中,這些值也在第二個作業表中。
任何人都可以協助一個簡單的代碼?我確實嘗試過四處尋找,但無法找到一個完全像這樣作業的。
非常感謝!
Sub DelColumn()
Dim PUsersList As Worksheet
Dim SUsersCheck As Worksheet
Dim lrM As Long
Dim lrS As Long
Dim i As Long, m, MLookup As Range, SLookup As Range
Set PUsers= ThisWorkbook.Worksheets("Sheet1")
Set SUsers = ThisWorkbook.Worksheets("Sheet2")
Set PLookup = PUsers.Columns(1) '<< reference list
Set SLookup = SUsers.Columns(1) '<< reference list
lrM = PUsers.Cells(PUsers.Rows.Count, "A").End(xlUp).Row
lrS = SUsers.Cells(SUsers.Rows.Count, "A").End(xlUp).Row
' here is where I'm stuck...
MsgBox "Update Complete"
End Sub
uj5u.com熱心網友回復:
一本作業簿,有 2 張紙。我撰寫了一些示例用戶名并從表 2 中洗掉了兩個用戶名。我在代碼中添加了注釋以幫助解釋。
Sheet1 圖片

Sheet2 影像

Sub deleteUsersThatDoNotExists()
Dim FindString As String
Dim Rng As Range
'get the value from the first row. in column A
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
'loop the rows in sheet 1
For i = 1 To LastRow
'get the value from sheet 1 to search in sheet 2
searchValue = Cells(i, 1)
'get current address in the loop for the current cell.
currentAddress = Cells(i, 1).Address
FindString = searchValue
If Trim(FindString) <> "" Then
With Sheets("Sheet2").Range("A:A")
Set Rng = .Find(What:=FindString, _
After:=.Cells(1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
If Not Rng Is Nothing Then
'found the user.
Debug.Print (searchValue " " "found")
Else
'did not find the user so lets delete but notice that i use clear and not delete
'so that we dont end up shifting rows up.
Range(currentAddress).Clear
End If
End With
End If
Next
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361274.html
上一篇:洗掉復制粘貼的范圍N次
下一篇:VBA將日期轉換為字串
