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

我想要做的是非常基本的。 我想遍历整个列“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 …循环的错误?

您有向后的值赋值,需要使用“ 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以便它继续外部循环。

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

最后,我去了太强大的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