【发布时间】:2020-07-03 15:21:55
【问题描述】:
我需要编写一些代码来选择对应于另一列中各行的相等单元格值的最小单元格块。这是我所拥有的:
Function MoveDown(c)
MoveDown = c.Offset(0, 1).Select
End Function
Sub LoanOptimization()
For Each c In Worksheets("Sheet1").Range("C1:C65536").Cells
c1 = c.Row
Do While c.Value = MoveDown(c).Value
c = MoveDown(c)
c2 = MoveDown(c).Row
Set CellRange = ActiveSheet.Range(Cells(c1, 12), Cells(c2, 12)).Select
Minimum = Application.WorksheetFunction.Min(CellRange)
Loop
Next
Range("N3").Select
ActiveSheet.Paste
End Sub
- 这对我正在尝试做的事情是否有意义,并且
- 如何将最小值变量中的值粘贴到另一列中
编辑:
我更改并添加到我的代码中,因为我的第一个问题只是我需要做的第一步。这是我所拥有的,但我不断收到编译错误:
Dim lastRow As Integer
Dim i As Integer
Dim comp1 As Integer
Dim comp2 As Integer
Dim rngCount As Integer
Dim minimum As Integer
Dim comp3 As Integer
Dim comp4 As Integer
lastRowDate = WorksheetFunction.CountA(Range("G:G")) 'Find the last row with data
lastRowNotional = WorksheetFunction.CountA(Range("L:L"))
rngCount = 0
For i = 1 To lastRowDate
comp1 = ActiveSheet.Cells(i, 7).Value 'Set comp1 equal to the Value of the cell in Column C at the current row in the For loop
comp2 = ActiveSheet.Cells(i + 1, 7).Value 'Set comp2 equal to the value of the cell just below it
If comp1 <> comp2 Then 'If the values are different, i.e. we've found the last item in a series of matches
minimum = Application.WorksheetFunction.Min(Range(Cells(i, 12), Cells(i - rngCount, 12))) 'Find the minimum of the range of cells
'from Row i in Column D to Row i - rngCount (which is were our series of matches began)
Cells(i, 14).Value = minimum 'Paste the found minimum in Column N, Row i
rngCount = 0 'Because the values no longer match, reset our counter
For j = 1 To lastRowNotional
comp3 = ActiveSheet.Cells(i, 14)
comp4 = ActiveSheet.Cells(i + 1, 14)
offset1 = ActiveSheet.Cells(i - 1, 14)
If (comp3 = offset1) And (comp3 <> comp4) Then 'If the selected cell is the last in a block of minima,
'then we want to replace that cell only with sum of the values in that block
Summation = Application.WorksheetFunction.Sum(Range(Cells(i, 12), Cells(i - rngCount, 12)))
Cells(i, 14).Value = Summation
End If
Else 'If the values are the same
rngCount = rngCount + 1 'increment our range counter until the values do not match
End If
Next i
【问题讨论】:
-
请参阅this 了解一些基本技巧。
-
另外,我认为您正在使这比现在更复杂。你能准确描述你想做什么吗?我认为这只是在指定的单元格范围内获得最小值,是吗?
-
如果 C5:C10 的单元格范围相同,那么我想从 L5:L10 获取块的最小值并将所有这些粘贴到新列中。等等等等……