LEN()在VBA中返回错误的值
我有这个简单的数据集:
230 16000 230 230000 230000 230000 16000000 230000 230000
我想要的是获得每个细胞的长度,但是当我写这个代码:
Sub LengthOfCell() Dim c As Long Dim result As Integer c = ActiveCell.Value result = Len(c) Debug.Print (result) End Sub
它给我2为第一个单元格(230),当它应该是3和4的任何数字超过3个数字。 不知道我做错了什么。 这只是为了certificate更大的SUB的概念:
Public Sub SortMyData() 'approach: convert line to string and concatenate to that as it's a lot less picky than Excel's formats, then replace cell value with the new string. ' Excel will then define the string type as either Percentage or Scientific depending on the magnitude. Dim i As Integer Dim N_Values As Integer N_Values = Cells(Rows.Count, 2).End(xlUp).Row 'Range("B6", Range("B5").End(xlDown)).Count For i = 6 To N_Values 'iteration loop from 6 (first row of value) to N_Values (last filled row) Cells(i, 3).NumberFormat = "0" If Cells(i, 2).NumberFormat <> "0.0%" Then Cells(i, 2).NumberFormat = "0.0%" Cells(i, 2).Value = Cells(i, 2).Value / 100 ElseIf Len(Cells(i, 3).Value > 3) Then Cells(i, 3).Value = Cells(i, 3).Value / 1000 ElseIf Cells(i, 3).Value = Null Then Cells(i, 3).Value = 0 Else Cells(i, 2).Value Cells(i, 3).Value End If ' If Len(Cells(i, 3) > 3) Then ' Cells(i, 3).Value = Cells(i, 3).Value / 1000 ' ElseIf Cells(i, 3).Value = Null Then 'Cells(1, 3).Value = 0 ' Else ' Debug.Print ' End If Next End Sub
结束)
是在错误的地方。
If Len(Cells(i, 3).Value > 3) Then
应该
If Len(Cells(i, 3).Value) > 3 Then
Len(Cells(i, 3).Value > 3)
将评估为Len("True")
或Len("False")
,所以它总是为True(任何非零数字为True)
Len是一个Stringtypes的函数
请问@Shai Rado,在新手答案中请小心…
F1:Len函数
返回Long,其中包含string中的字符数或存储variables所需的字节数 。
不知道为什么你要包含Dim c As Long
作品 – 为什么不试试这个:
Sub LengthOfCell() Dim result As Integer result = Len(ActiveCell.Value) Debug.Print (result) End Sub
这对我来说很好
由于您正在查找单元格中的字符数(数字),因此需要将其更改为Dim c As String
并稍微修改您的代码,它会给出您正在查找的结果。
请参阅下面的短文:
Sub LengthOfCell() Dim c As String Dim i As Long Dim result As Integer For i = 1 To 9 c = CStr(Cells(i, 1).Value) result = Len(c) Debug.Print result Next i End Sub
价值和展示文字之间似乎存在混淆。 Range().Value
将返回范围原始值,其中as, Range().Text
或Cstr(Range().Value)
将返回格式化的值。
Sub Demo() Dim r As Range For Each r In Range("A2:A9") r.Value = 230 r.Offset(0, 1) = r.NumberFormat r.Offset(0, 2) = Len(r.Value) r.Offset(0, 3) = Len(r.Text) r.Offset(0, 4) = Len(CStr(r.Value)) Next End Sub