循环Excel VBA中的单元格值

时间:2014-08-27 20:08:29

标签: excel vba excel-vba

我一直在尝试编写一个程序,它将循环遍历Excel工作表中的所有单元格,如果以“#”开头,​​它应该显示一条消息。这是代码:

(模板是工作表变量)

Private Function processTemplate()
    Dim total As Long
    total = template.UsedRange.count

    Dim count As Integer
    count = 0
    While count <= total
        If template.Cells(count).Value Like "[#]*" Then 'Here I get a error
            MsgBox "Found #"
            End If
        count = count + 1
    Wend
End Function

我已将错误隔离到在cells()中使用变量。如果我用一些数字(如8)替换计数,它工作正常。我在第If template.Cells(count).Value Like "[#]*" Then行收到错误1004 如果我总计Integer它在同一个地方有相同的错误。经过大约2-3小时的研究/将我的头撞在墙上我不知道。在将template.cells(row, col).Value分配给字符串变量时,我最初遇到错误。

现在是我的代码:

Private Sub processTemplate()
    MsgBox Len("")
    Dim str As String
    Dim rows As Long
    Dim cols As Long
    rows = template.UsedRange.Height
    cols = template.UsedRange.Width

    Dim row As Integer
    row = 1
    While row < rows
        Dim col As Integer
        col = 1
        While col < cols
            str = template.Cells(row, col).Text
            If Len(str) > 0 Then
                If Left(template.Cells(row, col).Text, 1) = "#" Then
                    MsgBox "Found IT"
                End If
            End If
            Rem MsgBox template.Parent.Name & ": " & template.Name & ", Cell(" & row & ", " & col & "): " & template.Cells(row, col).Value
            col = col + 1
        Wend
        row = row + 1
    Wend
End Sub

现在我收到str = template.Cells(row, col).Text

上的错误

2 个答案:

答案 0 :(得分:0)

我们可以使用而不是功能

我们遍历 UsedRange 中的所有单元格,寻找作为单元格中的第一个字符。

Sub FindThePound()
    Dim r As Range, pound As String, template As Worksheet
    pound = "#"
    Set template = ActiveSheet
    For Each r In template.UsedRange
        If Left(r.Value, 1) = pound Then
            MsgBox "Found # in " & r.Address(0, 0)
        End If
    Next r
End Sub

修改#1

此版本循环遍历所有单元格,但不测试包含公式的单元格

Sub FindThePound()
    Dim r As Range, pound As String, template As Worksheet
    pound = "#"
    Set template = ActiveSheet
    For Each r In template.UsedRange
        If r.HasFormula = False Then
            If Left(r.Value, 1) = pound Then
                MsgBox "Found # in " & r.Address(0, 0)
            End If
        End If
    Next r
End Sub

答案 1 :(得分:0)

你可以使用find / find next函数,我觉得比循环遍历每个单元格更快,并进行字符串比较。

With Worksheets(1).Range("a1:a500") 'Provide the search range
    Set c = .Find(2, lookin:=xlValues) ' searching for  2 in cell value
    If Not c Is Nothing Then 
        firstAddress = c.Address 'first occurance
        Do 
            'do whatever you want to do with the matches even replace them
            c.Value = 5 
            Set c = .FindNext(c) 
        Loop While Not c Is Nothing And c.Address <> firstAddress 
    End If 
End With

参考: http://msdn.microsoft.com/en-us/library/office/ff196143(v=office.15).aspx