Excel VBA Range.Value是Variant而不是String

时间:2016-12-01 13:52:02

标签: excel vba excel-vba

我有一个启用宏的Excel工作簿,当它启动时,它编辑了一些单元格并且我有一个更改事件,现在我希望更改事件不在启动时运行,而是在用户进行更改时运行,因为它在是的,target.value变成了一个变体,因此在将值赋给字符串变量时崩溃,这里是代码:

If Not Intersect(Target, Range("H83:H102,K83:K102,N83:N102,Q83:Q102,T83:T102,W83:W102,Z83:Z102,AC83:AC102")) Is Nothing Then
    Dim rowNum As Integer
    rowNum = Target.row
    Dim family As String
    family = Target.Offset(0, -1).Value
    Dim selection As String
    selection = "G" & rowNum & ",J" & rowNum & ",M" & rowNum & ",P" & rowNum & ",S" & rowNum & _
        ",V" & rowNum & ",Y" & rowNum & ",AB" & rowNum
    Select Case family
        Case "FAMILY 1"
            Call validateFamMembers(Target, selection, family, "C64")
        Case "FAMILY 2"
            Call validateFamMembers(Target, selection, family, "I64")
        Case "FAMILY 3"
            Call validateFamMembers(Target, selection, family, "O64")
        Case "FAMILY 4"
            Call validateFamMembers(Target, selection, family, "U64")
        Case "FAMILY 5"
            Call validateFamMembers(Target, selection, family, "C76")
        Case "FAMILY 6"
            Call validateFamMembers(Target, selection, family, "I76")
        Case "FAMILY 7"
            Call validateFamMembers(Target, selection, family, "O76")
        Case "FAMILY 8"
            Call validateFamMembers(Target, selection, family, "U76")
    End Select
End If

启动时代码在此行崩溃

family = Target.Offset(0, -1).Value

我该如何处理。提前致谢

1 个答案:

答案 0 :(得分:2)

我认为当您选择第一列时会出现问题。由于偏移,它会爆炸,因为它在第一列之后不能达到-1列。

编辑:

评论中的答案: 你使用Target。因此,如果选择更多单元格,则目标中会有更多单元格。并且多个单元格无法转换为字符串,因为它们是变体。