這是你的子程序的版本將存儲在下一列的電流值,如果它是已儲存的最後的值不同:
Sub CopyPasteHistorical()
Dim sht1Rng As Range, cell As Range
Dim lastCol As Long
With Worksheets("AAG") '<-- reference Sheet1
Set sht1Rng = .Range("I1", .Cells(.Rows.Count, "I").End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- set range with its column "I" cells containing constant (i.e. not formulas) values
End With
With Worksheets("Sheet2") '<-- reference Sheet2
For Each cell In sht1Rng '<-- loop through Sheet1 range
'determine last used column in row we are processing
lastCol = .Cells(cell.Row, .Columns.Count).End(xlToLeft).Column
If lastCol < 3 Then
'if the last used column on the row is before column C
'we need to store this value in column C
.Cells(cell.Row, 3).Value = cell.Value
ElseIf cell.Value <> .Cells(cell.Row, lastCol).Value Then
'if the last value on the row is different to the current value
'we need to store this value in the next column to the right
.Cells(cell.Row, lastCol + 1).Value = cell.Value
End If
Next cell
End With
End Sub
這裏是一個版本你的子程序將只存儲當前的值,如果它之前從未被使用:
Sub CopyPasteHistorical()
Dim sht1Rng As Range, cell As Range
Dim Col As Long
Dim lastCol As Long
Dim blnMatched As Boolean
With Worksheets("AAG") '<-- reference Sheet1
Set sht1Rng = .Range("I1", .Cells(.Rows.Count, "I").End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- set range with its column "I" cells containing constant (i.e. not formulas) values
End With
With Worksheets("Sheet2") '<-- reference Sheet2
For Each cell In sht1Rng '<-- loop through Sheet1 range
'determine last used column in row we are processing
lastCol = .Cells(cell.Row, .Columns.Count).End(xlToLeft).Column
If lastCol < 3 Then
'if the last used column on the row is before column C
'we need to store this value in column C
.Cells(cell.Row, 3).Value = cell.Value
Else
'see if this value has already been stored
blnMatched = False
For Col = 3 To lastCol
If cell.Value = .Cells(cell.Row, Col).Value Then
blnMatched = True
Exit For
End If
Next
'if the current value doesn't match any previous values
'we need to store this value in the next column to the right
If Not blnMatched Then
.Cells(cell.Row, lastCol + 1).Value = cell.Value
End If
End If
Next cell
End With
End Sub
當然,你應該查找「找到工作表中的下一個空單元格」,你可以做一些類似於工作表(「Sheet1」)。Range(「A1」).End(xlDown).Row + 1',或者只是'Offset()'。 – BruceWayne
謝謝!這是否會在代碼的末尾或兩行之間的某處出現?我爲基本問題表示歉意,我剛開始學習VBA! –