2017-04-07 21 views
1

我想要做的事情非常基本。我想遍歷整列「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,以便它繼續外部循環。

+0

太棒了!這工作。但它並沒有在整個專欄中循環。它只停留在第一列(在本例中爲「I1」,然後停止)。任何想法?感謝您的快速和很好的迴應。 –

+0

你可以通過使用'Like'來簡化它:例如'如果asciinum like'[aeiou]「Then' – CLR

0

你不需要宏找到它,公式會做 - 假設A1是你檢查電池,=MID(A1,FIND({"a","e","i","o","u"},A1),1)會做

+0

這可能是非常好的,但是嗯,我打算對每一行做很多驗證,所以我需要管理它們,並且我很容易在VBA中執行它(因爲我是Java/C#用戶)。這只是第一個。如果您有任何想法,我將不勝感激。謝謝你的迴應:) :) –

+0

至少使用instr而不是循環所有的字母 – Lowpar

0

最後,我去了正則表達式的太強大的黑暗藝術:

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 
相關問題