excel - 列中子字符串的最大值

标签 excel vba string substring max

鉴于我有一列采用以下格式的值

01.2020
12.2021
3.2019
02.2020
etc.

超过一百万行左右,我想要一个 VBA 函数来查找句点左侧数字的最大值。

类似于

Option Explicit

Sub test()
    Dim r As Range, c As Range
    Dim max As Long, current As Long
    Dim s As String
    
    With År_2020
        Set r = .Range(.Range("D2"), .Range("D" & .Rows.Count).End(xlUp))
    End With
    
    For Each c In r
        current = CLng(Left(c, InStr(1, c, ".", vbBinaryCompare) - 1))
        If current > max Then max = current
    Next c
    
    Debug.Print max
End Sub

可行,但我觉得应该有一个更简单的解决方案。

有人可以就是否可以找到更简单的解决方案提供一些意见吗?

最佳答案

公式解决方案

enter image description here

  • B1 中的公式:=VALUE(LEFT(A1,FIND(".",A1)-1))
  • 在 C1 中:=MAX(B:B)

VBA 解决方案

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")

Dim LastRow As Long 'find last used row
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

Dim ValuesToConvert() As Variant 'read data into array
ValuesToConvert = ws.Range("A1", "A" & LastRow).Value 'will throw an error if there is only data in A1 but no data below, make sure to cover that case

Dim iVal As Variant
For iVal = LBound(ValuesToConvert) To UBound(ValuesToConvert)
    'truncate after period (might need some error tests if period does not exist or cell is empty)
    ValuesToConvert(iVal, 1) = CLng(Left(ValuesToConvert(iVal, 1), InStr(1, ValuesToConvert(iVal, 1), ".") - 1))
Next iVal

'get maximum of array values
Debug.Print Application.WorksheetFunction.Max(ValuesToConvert)

关于excel - 列中子字符串的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66064144/

相关文章:

excel - 适用于 Excel 2010/2007/2003 的日期选择器

Python - 如何改变像é这样的字母

java - 解析特殊格式的字符串

excel - 如何从 VBA 代码更改图表的子类型

vba - 在一个单元格内查找具有不同字符串的匹配单元格

Excel/VBA - 使用动态范围的索引匹配函数

java - ArrayList自己的类型转String?

R 代码要求 Excel 打开文件

excel - application.ontime 未取消或在后台运行

excel - 查找特定列中最后使用的单元格以及范围周围的边框