在列中find最大值,select相应的值,复制并粘贴这些值

我的问题描述如下:我有一个表列的长度变化。 我想在列4中search最小值,然后将最小值的行复制到第6行

这是我的代码:

Sub TestMax() Dim searchArea As Range Dim searchResult As Range Dim rowMax As Long Dim maxValue As Long Dim columnSearch As Integer Dim lastRow As Long columnSearch = 4 'Select all the cells in the column you want to search down to the first empty cell. lastRow = Sheets("V&A 16").Range("B1048576").End(xlUp).Row Range(Cells(8, 4), Cells(lastRow, 4)).Select Set searchArea = Range(Cells(8, 4), Cells(lastRow, 4)) 'Determine the max value in the column. maxValue = Application.Max(searchArea) 'Find the row that contains the max value. Set searchResult = Sheets("V&A 16").Columns(columnSearch).Find(What:=maxValue, _ After:=Sheets("V&A 16").Cells(8, columnSearch), LookIn:=xlValues, LookAt:=xlWhole, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _ SearchFormat:=False) 'Store the row that contains the minimum value in a variable. rowMax = searchResult.Cells.Row searchResult.Select Range(Cells(rowMax, 3), Cells(rowMax, 13)).Select Selection.Copy Range("C6").Select ActiveSheet.Paste Link:=True End Sub 

由于某种原因,我不断收到错误。 尽pipe与Application.Min完全相同的代码,而不是最大工程。 安妮帮忙吗? 提前致谢!!

虽然适当的解决scheme可能会重做大部分代码,并且可能会在代码中讨论variables名称和固定值,但是我觉得这可能不会帮助您逐步实现。

所以,对于初学者,我会build议以下(如果你是VBA的新手):

首先,我会改变

 maxValue = Application.Max(searchArea) 

对此

 maxValue = Application.WorksheetFunction.Max(searchArea) 

然后拿到rowMax

 rowMax = Application.WorksheetFunction.Match(maxValue, searchArea, 0) 

(你可以靠近)

笔记:

  • 这只有在列4(您的search区域)中只有不同的值时才有效。 否则事情可能会变得更复杂一些,这可以通过对数据进行sorting而大大减less
  • rowmax将在这种情况下返回您的search范围内的目标。
  • 因为“search范围”从修正8开始,你可以做“rowmax = awf.match + 8”…也就是说,如果你之后select不使用searchArea-Range

编辑:试试这个。 正如我所说,虽然这种方法可能有点可怕,但从学习的angular度来看,最好保留迄今为止所做的,只是将其改为“以某种方式工作”。 希望有所帮助!

 Sub TestMax() Dim searchArea As Range Dim rowMax As Long Dim maxValue As Long Dim lastRow As Long columnSearch = 4 'get the lastrow lastRow = Sheets("V&A 16").Range("B1048576").End(xlUp).Row 'set the search area Set searchArea = Range(Cells(8, columnSearch), Cells(lastRow, columnSearch)) 'Find the row that contains the max value inside the search area rowMax = Application.WorksheetFunction.Match( _ Application.WorksheetFunction.Max(searchArea), searchArea, 0) 'clumsily copy+paste (alternative: set values instead of copying) 'searchArea.Cells(rowMax, columnSearch).EntireRow.Copy 'Cells(6, columnSearch).EntireRow.Select 'ActiveSheet.Paste ' Alternative: ActiveSheet.Rows(6).Cells().Value = searchArea.Rows(rowMax).EntireRow.Cells.Value End Sub 

您可以遍历第4列来查找对应于最小值的行,并将该行复制到第6行

(例如:考虑10,000行数据进行检查)

 Sub Foo() smallest = Cells(1, 4).Value i = 1 For i = 2 To 10000 If Cells(i, 4).Value < smallest And Cells(i, 4).Value <> "" Then smallest = Cells(i, 4).Value Row = i End If Next i Rows(Row & ":" & Row).Select Selection.Copy Rows("6:6").Select ActiveSheet.Paste End Sub