在Excel VBA中循环单元格值

我一直在试图编写一个程序,它将循环遍历Excel表格中的所有单元格,如果以'#'开始,它将显示一条消息。 这是代码:

(模板是一个工作表variables)

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 

我已经隔离在单元格内使用variables的错误()。 如果我replace一些数字(如8),它工作正常。 我得到错误1004在线If template.Cells(count).Value Like "[#]*" Then如果我让一个Integer它有相同的错误在同一个地方。 经过大约2-3小时的研究/敲我的头在墙上,我不知道。 我将template.cells(row, col).Value赋值给一个stringvariablestemplate.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

我们可以使用一个而不是一个函数

我们遍历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

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

 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 

你可以使用find / find下一个函数,这个函数比循环遍历每个单元格要快一些,并且做string比较。

 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