无法使用Range格式的字符串格式的单元格地址

时间:2016-08-29 11:33:53

标签: excel vba excel-vba

这是我拥有的数据集:

This is data set i have

我想获取包含Nikunj的单元格与包含Deepak的单元格之间的非空单元格计数。这是我正在使用的代码,

Sub Count()
Dim txt1 As String
Dim txt2 As String
txt1 = "Nikunj"
txt2 = "Deepak"
With Worksheets(1).Range("b1:b20")
    Set a = .Find(txt1, LookIn:=xlValues)
    Set b = .Find(txt2, LookIn:=xlValues)
End With

arra = Split(a.Address, "$")
arrb = Split(b.Address, "$")
newa = Join(arra, "")
newb = Join(arrb, "")

MsgBox WorksheetFunction.CountA(Range("newa:newb")) 
End Sub

我面临的问题是我的 xlA1 格式的单元格地址为 newa newb ,我无法使用 WorksheetFunchtion.CountA

基本上我需要帮助将单元格的地址从字符串转换为接受范围的格式。

我是VBA的新手,也不经常在这里发帖询问。如果问题不符合现场标准,请原谅我。

4 个答案:

答案 0 :(得分:5)

您可以将Range(a, b)传递给CountA,而无需解析单元格地址:

Option Explicit

Sub Count()

    Dim txt1 As String
    Dim txt2 As String
    Dim a As Range
    Dim b As Range

    txt1 = "Nikunj"
    txt2 = "Deepak"

    With Worksheets(1).Range("b1:b20")
        Set a = .Find(txt1, LookIn:=xlValues)
        Set b = .Find(txt2, LookIn:=xlValues)
    End With

    MsgBox WorksheetFunction.CountA(Range(a, b))

End Sub

答案 1 :(得分:4)

您当前的问题是"newa:newb"是一个实际包含字符“newa:newb”的字符串,而不是存储在变量newanewb中的字符。要连接字符串变量,请使用&运算符:

newa & ":" & newb
然而,正如Robin Mackenzie指出的那样,这不是必要的

MsgBox WorksheetFunction.CountA(Range(a, b))

也应该这样做。

顺便说一下,replace函数是从字符串中删除字符的更简单方法

newa = Replace(a.Address, "$", "")

修改:建议您使用Option Explicit

答案 2 :(得分:1)

您可以直接使用该地址:

Sub Count()
    Dim txt1 As String
    Dim txt2 As String
    Dim a As Range, b As Range

    txt1 = "Nikunj"
    txt2 = "Deepak"
    With Worksheets(1).Range("b1:b20")
        Set a = .Find(txt1, LookIn:=xlValues)
        Set b = .Find(txt2, LookIn:=xlValues)
    End With

    MsgBox WorksheetFunction.CountA(Range(a.Address & ":" & b.Address))
End Sub

enter image description here

答案 3 :(得分:1)

未请求,但没有VBA的选项:

=COUNTA(INDIRECT("B"&MATCH("Nikunj",B:B,0)&":B"&MATCH("Deepak",B:B,0)))