简体   繁体   English

计算行数,直到找到特定的字符串

[英]Count Rows Until Finding Specific String

I am trying to use Excel VBA to count the number of rows until I hit a specific string and set a variable equal to it. 我试图使用Excel VBA计算行数,直到我命中特定的字符串并设置一个等于它的变量。

Something like: 就像是:

Dim i as Integer

i = Worksheets("Scope Phase Document").Range("A1", Range("A1").End(xlDown)).Find("FACTS - What are we measuring?").Count

I know this isn't the correct syntax and I'm probably missing other stuff, but just using the different functions I currently know, this is what I would hope would do the trick. 我知道这不是正确的语法,而且我可能会缺少其他内容,但是仅使用我当前知道的不同功能,这就是我希望能够解决的问题。 I get 我懂了

Run-time error '91' saying "Object variable or With block variable not set 运行时错误“ 91”,提示“未设置对象变量或带块变量

I have tried a few different ways of doing it, but can't figure out a way that doesn't result in an error. 我尝试了几种不同的方法来完成此操作,但无法找出不会导致错误的方法。

So I want to start at A1 and count all the rows down until I reach the specific string "FACTS - What are we measuring?". 因此,我想从A1开始,对所有行进行递减计数,直到到达特定的字符串“事实-我们正在测量什么?”。

Any help would be greatly appreciated! 任何帮助将不胜感激!

I prefer MATCH, but if the match is not found it throws an error. 我更喜欢MATCH,但是如果找不到匹配项,则会引发错误。 So we need to test for that: 因此,我们需要对此进行测试:

Dim i As Long
i = 0
On Error Resume Next
i = Application.WorksheetFunction.Match("FACTS - What are we measuring?", ActiveSheet.Range("A:A"), 0)
On Error GoTo 0
If i > 0 Then
 ' do you stuff with i
End If

So you basically want MATCH() : 所以你基本上想要MATCH()

=MATCH("FACTS - What are we measuring?",A:A,0)

It returns the row number of matched string. 它返回匹配字符串的行号。

Your code is fine except you should use the Row property. 您的代码很好,但您应该使用Row属性。 The Count property as you have used it will return 1 because the Find method returns one cell (the first cell where a match is found). 您使用过的Count属性将返回1,因为Find方法返回一个单元格(找到匹配项的第一个单元格)。

Dim i as Integer

i = Worksheets("Scope Phase Document").Range("A1", Range("A1").End(xlDown)).Find("FACTS - What are we measuring?").Row

Like Scott mentioned, if your text is not found, Excel will throw an error. 就像Scott提到的那样,如果找不到您的文本,Excel将引发错误。

I'd do this: 我会这样做:

Sub rowcounter()

Dim i As Integer

Range("A1").Select

i = 0

Do

Selection.Offset(1, 0).Select

i = i + 1

Loop Until Selection.Value = "FACTS - What are we measuring?"

MsgBox "rows count is " & i

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM