vba 如何检查单元格值中的第一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34713100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:09:35  来源:igfitidea点击:

How to check first character in a cell value

vbaexcel-vbaexcel

提问by mrwave

I was wondering if there is a way to check the first character in a cell value.

我想知道是否有办法检查单元格值中的第一个字符。

E.g

例如

01999102477490 ( first char "0" )

11003200602650 (first char "1" )

What I am trying to accomplish is to use an IF statement to distinguish cell values according to "0" and "1" and assign them to different columns. I can probably make the statement on my own, I just need to know how to check the first character for "0" and "1".

我想要完成的是使用 IF 语句根据“0”和“1”区分单元格值并将它们分配给不同的列。我可能可以自己做出声明,我只需要知道如何检查“0”和“1”的第一个字符。

I should also say that I have whole column of values to check

我还应该说我有一整列值要检查

回答by 0m3r

Try:

尝试:

Option Explicit
Sub FirstChar()
    Dim xlString As String
    Dim xlFirstChar As String

    xlString = "01999102477490"

    xlFirstChar = Left$(xlString, 1)

    MsgBox xlFirstChar
End Sub

String Manipulation

字符串操作

回答by Angelo DeMichaels

IF(logical_test, [value_if_true], [value_if_false])

Using the above you can do the following:

使用上述内容,您可以执行以下操作:

IF(LEFT(A1,1)="0","0",IF(LEFT(A1,1)="1","1","Neither"))

Replace A1 with the cell you want to test

将 A1 替换为您要测试的单元格

Replace the "0" between the commas with whatever you want to do with those values that start with 0

将逗号之间的“0”替换为您想要对以 0 开头的值执行的任何操作

Replace the "1" between the commas with whatever you want to do with those values that start with 1

将逗号之间的“1”替换为您想要对以 1 开头的值执行的任何操作

Replace "Neither" with whatever you want to do with those values that don't start with 0 or 1

用不以 0 或 1 开头的值替换“Neither”

回答by Angelo DeMichaels

A slightly different approach.

一种稍微不同的方法。

Dim a As Long, arr As Variant
With Worksheets("Sheet1")
    arr = .Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp)).Value
    For a = LBound(arr, 1) To UBound(arr, 1)
        Select Case Asc(arr(a, 1))  'might have to be .Range("A1").Text
            Case 48
                Debug.Print "it's a zero"
                'do something with arr(a, 1)
            Case 49
                Debug.Print "it's a one"
                'do something with arr(a, 1)
            Case Else
                Debug.Print "it's something else"
        End Select
    Next a
End With

By bulk loading the values in column A to a variant array and cycling through the array, you should same some read-time on the loop.

通过将 A 列中的值批量加载到变体数组并在数组中循环,您应该在循环中具有相同的读取时间。

If you can work with all of the zeroes at once and then all of the ones at once, consider a AutoFilter method.

如果您可以一次处理所有零,然后一次处理所有零,请考虑使用AutoFilter 方法