提取文本 - 无效的过程调用或参数

时间:2015-02-04 19:03:26

标签: excel excel-vba vba

我已经编写了这个VBA代码,我在第12行遇到错误(getName = Mid ..) - 无效的过程调用或参数。这样做的目的是找到一个紧密支架的第一个实例")"然后找到一个打开的第二个实例"("括号,并将这两个点之间的文本粘贴到下一列。有人可以解释为什么我会收到此错误吗?

Dim getName As String
    Dim part1 As Integer
    Dim part2 As Integer
    Dim part3 As Integer
    Dim rCell As Range
    Dim rRng As Range
    Set rRng = Sheet2.Range("B1:B10000")

    For Each rCell In rRng.Rows
    part1 = InStr(Path, ")")
    part2 = InStr(Path, "-")
    part3 = InStr(part2 + 1, Path, "(")
    getName = Mid(Path, part1 + 1, part3 - part1 - 1)
    Range("B1:B10000").Offset(RowOffSet:=0, ColumnOffset:=1).Select.Value = getName
    Next rCell
    '
    End Sub

我想解析的数据:

TEST2_ (LC) HELLO (brtreq) - dgfdag - 43224 - Dec 08 to Dec 31 2014 - Ros - 2gd - Skin

TEST MOBILE STIE (LC) MOODY (FEREFE) - RDEWF- Jan 15 to Dec 31 2015 - Ros - HRWFEW (New) (2F4F4)

TEST GPTDFV SGE (LC) GRASS (HSK) - GSK - 23F23 - Jan 06 to Jan 31 2015 - Ros - WERWE - PSDF

1 个答案:

答案 0 :(得分:2)

首先,始终使用Option Explicit。这将阻止您使用未声明的变量,这是您的错误的来源。

如果没有分配给该变量,您可以将空字符串或零值传递给Instr函数,并且您将查看是否调试了所有part1的值part2part3变量为0,这将导致该错误。

在分配给part变量时,你也有一些错误的逻辑,即将负数传递给Mid函数,这会引发错误。

试试这个。我将GetPath分隔为自己的函数调用:

Option Explicit
Sub foo()
Dim path As String
Dim rCell As Range
Dim rRng As Range

Set rRng = Sheet2.Range("A1:A3")

For Each rCell In rRng.Rows
    path = rCell.Value
    rCell.Offset(0,1).Value = GetName(path)
Next rCell

End Sub

Function GetName(path As String)

    Dim part1 As Integer
    Dim part2 As Integer
    Dim part3 As Integer
    Dim returnValue As String

    If Trim(path) = vbNullString Then GoTo EarlyExit 'handles empty strings

    part1 = InStr(path, ")")
    part2 = InStr(part1, path, ")") 'I changed this line
    part3 = InStr(part2 + 1, path, "(")

    returnValue = Trim(Mid(path, part1 + 1, part3 - part1 - 1))

EarlyExit:
    GetName = returnValue

End Function