下面是一些VBA代碼,您可以使用它循環顯示第一張工作表,並僅將第一個唯一行復制到第二張工作表。您的問題只是要複製的值,但此代碼會複製整個行。您可以輕鬆刪除不必要的列或修改代碼。
Option Explicit
Sub Main()
Dim wsSource As Worksheet
Dim wsDestination As Worksheet
Dim uniqueCol As String
Set wsSource = Worksheets("Sheet1")
Set wsDestination = Worksheets("Sheet2")
uniqueCol = "C"
CopyFirstUniqueValuesToOtherWorksheet _
wsSource, _
wsDestination, _
uniqueCol
End Sub
Sub CopyFirstUniqueValuesToOtherWorksheet(_
sourceSheet As Worksheet, _
destinationSheet As Worksheet, _
uniqueCol As String)
Dim iRow As Long
Dim iHeaderRow As Long
Dim rngUnique As Range
iHeaderRow = 1
iRow = iHeaderRow + 1
'Clear contents of destination sheet '
ClearDestinationSheet sourceSheet, destinationSheet
'Copy Header Row '
CopyRow sourceSheet, destinationSheet, iHeaderRow
'Loop through source sheet and copy unique values '
Do While Not IsEmpty(sourceSheet.Range("A" & iRow).value)
Set rngUnique = sourceSheet.Range(uniqueCol & iRow)
If Not ValueExistsInColumn(destinationSheet, uniqueCol, _
CStr(rngUnique.value)) Then
CopyRow sourceSheet, destinationSheet, iRow
End If
iRow = iRow + 1
Loop
End Sub
Sub CopyRow(sourceSheet As Worksheet, _
destinationSheet As Worksheet, _
sourceRow As Long)
Dim iDestRow As Long
sourceSheet.Select
sourceSheet.Rows(sourceRow & ":" & sourceRow).Select
Selection.Copy
iDestRow = 1
Do While Not IsEmpty(destinationSheet.Range("A" & iDestRow).value)
iDestRow = iDestRow + 1
Loop
destinationSheet.Select
destinationSheet.Rows(iDestRow & ":" & iDestRow).Select
ActiveSheet.Paste
sourceSheet.Select
End Sub
Sub ClearDestinationSheet(sourceSheet As Worksheet, _
destinationSheet As Worksheet)
destinationSheet.Select
Cells.Select
Selection.ClearContents
sourceSheet.Select
End Sub
Function ValueExistsInColumn(sheet As Worksheet, _
col As String, _
value As String) As Boolean
Dim rng As Range
Dim i As Long
i = 2
Do While Not IsEmpty(sheet.Range(col & i).value)
Set rng = sheet.Range(col & i)
If CStr(rng.value) = value Then
ValueExistsInColumn = True
Exit Function
End If
i = i + 1
Loop
ValueExistsInColumn = False
End Function