我正在尝试以最有效的方式使用VBA清理提供给我的excel数据集。我想比较工作表范围内3列的行值(#可能有所不同),如果所有3列的行值都相同,那么我希望将相同行但不同列的值复制到一个单元格中。>
最终想要
答案 0 :(得分:0)
将来,SO问题应该是关于您遇到的特定问题,而不是一般性问题。
这是一个VBA函数,它将:
这是子例程:
Sub clean_dataset()
Dim sh As Worksheet
Dim rw As Range
Dim workingRow As Integer
Dim col1Value As String
Dim col2Value As String
Dim col3Value As String
Dim rowCount As Integer
workingRow = 1
'Iterate through all rows on the sheet. Stop if we get to an empty row.
Set sh = ActiveSheet
For Each rw In sh.Rows
' Exit if we get to an emptry row.
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
' Check if our three columns to watch have changed value. If they have, we should be in a new 'working row'
If rw.Row > 1 Then
If (Range("A" & rw.Row).Value <> Range("A" & rw.Row - 1).Value) Or (Range("B" & rw.Row).Value <> Range("B" & rw.Row - 1).Value) Or (Range("C" & rw.Row).Value <> Range("C" & rw.Row - 1).Value) Then
workingRow = rw.Row
End If
End If
' Get the values in the current row from the dataset we are trying to consolidate.
col1Value = Range("D" & rw.Row).Value
col2Value = Range("E" & rw.Row).Value
col3Value = Range("F" & rw.Row).Value
' Add the values to the working row cells, if they do not already exist
If InStr(Range("D" & workingRow).Value, col1Value) = 0 Then
Range("D" & workingRow) = Range("D" & workingRow).Value & vbLf & col1Value
End If
If InStr(Range("E" & workingRow).Value, col2Value) = 0 Then
Range("E" & workingRow) = Range("E" & workingRow).Value & vbLf & col2Value
End If
If InStr(Range("F" & workingRow).Value, col3Value) = 0 Then
Range("F" & workingRow) = Range("F" & workingRow).Value & vbLf & col3Value
End If
' As long as we are not in the working row, delete the values
If rw.Row <> workingRow Then
Range("D" & rw.Row) = vbNullString
Range("E" & rw.Row) = vbNullString
Range("F" & rw.Row) = vbNullString
End If
rowCount = rw.Row
Next rw
' End of for each
' Go back through, and delete any rows that do not have values in column D
For iter = rowCount To 1 Step -1
' If all three columns are blank, delete the row.
If Range("D" & iter).Value = vbNullString Then
sh.Rows(iter).Delete
End If
Next
End Sub
希望这会有所帮助。
答案 1 :(得分:0)