我想要做的是非常基本的。我想遍历整列“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?
答案 0 :(得分:2)
您的价值分配向后,需要使用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
,以便继续外循环。
答案 1 :(得分:0)
您不需要宏来查找它,公式会做 - 假设A1
是您检查的单元格,=MID(A1,FIND({"a","e","i","o","u"},A1),1)
将会执行此操作
答案 2 :(得分:0)
最后,我选择了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