我正在嘗試創建一個 VBA 宏,其中要求用戶從輸入框中選擇范圍的列,如“A:A”。然后要求他們提供第二個列范圍,例如“C:C”。
一旦選擇了兩個范圍,我想讓 excel 比較兩個列范圍的重復項并將它們從第一個中洗掉。
例如,如果用戶選擇了 column range1 和 column range2。并且都有編號為 5 和 7 的單元格,我希望列 range1 洗掉所有 5 和 7 的單元格。
uj5u.com熱心網友回復:
我撰寫了一些 VBA 代碼,這些代碼將根據我對您在做什么的理解來執行此操作。但是,我假設資料量相對較小并且對效率的需求不大。另外,不用擔心任何錯誤處理等。
需要進行修改才能使其恢復原狀,以更穩健地執行。
選項顯式
Sub DeleteDupValuesInFirstSelectedColumn() '例程要求用戶選擇兩個范圍,然后'洗掉第一個列中重復的值'在第二個范圍中
Dim CWS As Worksheet
Dim SelRng As Range, Col1 As Range, Col2 As Range
Dim Cell1 As Range, Cell2 As Range
Set CWS = ActiveSheet
'Ask the user to select a range
Set SelRng = Application.InputBox( _
Title:="Range 1 Selection", _
Prompt:="Select the first column", _
Type:=8)
'Limit the selection to the first column in the used range
Set Col1 = Intersect(CWS.UsedRange, SelRng.Columns(1).EntireColumn)
'Ask the user to select a second range
Set SelRng = Application.InputBox( _
Title:="Range 2 Selection", _
Prompt:="Select the second column", _
Type:=8)
'Limit the selection again
Set Col2 = Intersect(CWS.UsedRange, SelRng.Columns(1).EntireColumn)
'Super inefficient. Relying on insignificant amounts of values
'Don't use loop within a loop for anything important
For Each Cell2 In Col2
For Each Cell1 In Col1
If Cell1.Value = Cell2.Value Then
'If the correct cells are being filled, uncomment the line to delete
Cell1.Interior.ColorIndex = 3
'Cell1.Delete Shift:=xlUp
End If
Next Cell1
Next Cell2
結束子
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348365.html
