How can I get the length of the longest string in a column (Excel)?

强颜欢笑 提交于 2020-01-03 09:02:09

问题


I have an Excel spreadsheet that I am writing out to a file. I am currently using the following method to reproduce the contents of each cell:

cell_contents = Right(Space(10) & Trim(Cells(iRow, iColumn)), 10)

However, if the contents of the cell are longer than 10 characters long (or however long I choose to specify), then I loose parts of the data. Is there a way to quickly and easily get the length of the longest string in a range of cells?

I have seen people suggest using the following loop, but I was hoping that I might be able to do it without having to loop over all the cells:

For Each c In SourceRange.Cells
   if len(c) > b then b = len(c)
Next c

回答1:


Record these steps as a macro in the cell you want to calculate the max length.

1) enter this formula

=MAX(LEN(A1:A4), 1) -- Edit for your range.

2) press control-shift enter (FormulaArray)

3) now stop recording macro

4) view the VBA. copy what you need to your VBA.

Should give you something like this:

Selection.FormulaArray = "=MAX(LEN(R[-10]C[1]:R[-1]C[1]))"



回答2:


Press Alt-F11, insert new module, paste code bellow.

Public Function maxRangeLength(data As Range) As Integer
    Dim ret As Integer

    ret = 0

    For Each cell In data
        ret = Application.Max(ret, Len(cell))
    Next cell

    maxRangeLength = ret
End Function

Usage:

=maxRangeLength(A8:D11)



回答3:


Suppose that the data is in column A and there is a heading row for your spreadsheet.

  1. Create a new column next to it and enter in the formula: =LEN(A2)
  2. Autofill down that formula.
  3. Turn on filtering for that column and the click the drop-down box on the column heading cell.
  4. Scroll down to the bottom of the list where the largest summarized value is.
    That will be the largest value in the column.


来源:https://stackoverflow.com/questions/23678242/how-can-i-get-the-length-of-the-longest-string-in-a-column-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!