在一列中查找第一个元音并将其显示在下一列中

Find first vowel in a column and display it in the next column

我想做的是非常基础的。我想遍历整个列 "I",然后在列 "M" 中显示这个元音。但我想遍历该列中的所有 1000 多行。到目前为止,这是我得到的结果,但我在引用基于对象时遇到错误。

Private Sub Form_Load()
    Dim mystring As String, i As Long, asciinum As String, f As Long

    For f = 1 To Rows.Count
        Rows(f, "I") = mystring
        For i = 1 To Len(mystring)
            asciinum = LCase(Mid(mystring, i, 1))
            If asciinum = "a" Or asciinum = "e" Or asciinum = "i" Or asciinum = "o" Or asciinum = "u" Then
                Rows(f, "M") = "First Vowel " + asciinum
                Exit For
            End If
        Next
        Exit For
    Next
End Sub

数组和 For...Loop 可能有错误?

你不需要宏来找到它,一个公式就可以了 - 假设 A1 是你检查的单元格,=MID(A1,FIND({"a","e","i","o","u"},A1),1) 就可以了

您的值赋值是反向的,需要使用 Cells 而不是 Rows

Option Explicit

Private Sub Form_Load()
    Dim mystring As String, i As Long, asciinum As String, f As Long

    For f = 1 To Rows.Count
        mystring = Cells(f, "I").Value2
        For i = 1 To Len(mystring)
            asciinum = LCase(Mid(mystring, i, 1))
            If asciinum = "a" Or asciinum = "e" Or asciinum = "i" Or asciinum = "o" Or asciinum = "u" Then
                Cells(f, "M") = "First Vowel " + asciinum
                Exit For
            End If
        Next
        Exit For
    Next
End Sub

这应该适用于 ActiveSheet,但您应该开始练习使用已定义的父工作表,并且只使用其中包含值的单元格,而不是一直循环到工作表的底部。

Option Explicit

Private Sub Form_Load()
    Dim mystring As String, i As Long, asciinum As String, f As Long

    With Worksheets("sheet1")
        For f = 1 To .Cells(.Rows.Count, "I").End(xlUp).Row
            mystring = .Cells(f, "I").Value2
            For i = 1 To Len(mystring)
                asciinum = LCase(Mid(mystring, i, 1))
                If asciinum = "a" Or asciinum = "e" Or asciinum = "i" Or asciinum = "o" Or asciinum = "u" Then
                    .Cells(f, "M") = "First Vowel " + asciinum
                    Exit For
                End If
            Next i
        Next f
    End With
End Sub

我还删除了第二个 Exit For 以便它继续外循环。

最后,我选择了 RegEx 强大的黑魔法:

Private Sub Form_Load()

    'Requires reference to "Microsoft VBScript Regular Expression 5.5"

    Dim mystring As String, i As Long, asciinum As String, f As Long
    Dim regFindVowels As New RegExp
    Dim FoundVowels As Variant
    regFindVowels.Pattern = "[AEIOUaeiou]"
    regFindVowels.Global = True

    With Worksheets("Sheet 1") ' change this to your sheetname
        For f = 1 To .Cells(.Rows.Count, "I").End(xlUp).Row
            Set FoundVowels = regFindVowels.Execute(.Cells(f, "I").Value2)
            If FoundVowels.Count > 0 Then .Cells(f, "M") = "First Vowel " + FoundVowels(0) ' (0) is first, (1) is second etc.
        Next
    End With

End Sub