Excel中的VBA错误:无效使用属性

时间:2014-07-27 09:28:36

标签: excel vba excel-vba

我在CommandButton_Click()中编写了以下代码,但它出现以下错误:

  

编译错误:无效使用属性。

Public Sub SectorNAme()
  Dim score As String, result As Integer
  Dim a_counter As Integer

  For a_counter = 1 To 473
    score = Range("AB" + a_counter).Value

    If score = "Technology & FM" Then
      result = "25"
    ElseIf score = "Operating Equipment & Supplies" Then
      result = "26"
    ElseIf score = "Interiors & Design" Then
      result = "27"
    ElseIf score = "Outdoor & Resort Experience" Then
      result = "28"
    ElseIf score = "HORECA" Then
      result = "29"
    ElseIf score = "Retail & Franchise" Then
      result = "30"
    ElseIf score = "Design" Then
      result = "33"
    ElseIf score = "Health & Fitness Eqpts, P&S" Then
      result = "32"
    ElseIf score = "Recreational Fun & Adventure" Then
      result = "31"
    Else
      result = "35"

    Range("AC" + a_counter).Value

    End If
  Next a_counter
End Sub

请帮我找一个解决方案。

1 个答案:

答案 0 :(得分:6)

你有一些小问题:

  1. 您获得的错误位于:

    Range("AC" + a_counter).Value
    

    我认为你打算这样做:

    Range("AC" + a_counter).Value = result
    
  2. 这个:Range("AB" + a_counter)而且:Range("AC" + a_counter)应该使用&而不是+来连接字符串,否则会出现类型不匹配,即: Range("AB" & a_counter)Range("AC" & a_counter)

  3. 我刚刚编辑了您的问题,并且通过更好的缩进,我还注意到您的End IfRange("AC" + a_counter).Value之后,这是错误的。它应该之前,否则您的结果只会在Else案例中分配,而不会在其他任何案例中分配。

  4. 因此,您的最终代码应如下所示:

    Public Sub SectorName()
    
      Dim score As String, result As Integer
      Dim a_counter As Integer
    
      For a_counter = 1 To 473
        score = Range("AB" & a_counter).Value
    
        If score = "Technology & FM" Then
          result = "25"
        ElseIf score = "Operating Equipment & Supplies" Then
          result = "26"
        ElseIf score = "Interiors & Design" Then
          result = "27"
        ElseIf score = "Outdoor & Resort Experience" Then
          result = "28"
        ElseIf score = "HORECA" Then
          result = "29"
        ElseIf score = "Retail & Franchise" Then
          result = "30"
        ElseIf score = "Design" Then
          result = "33"
        ElseIf score = "Health & Fitness Eqpts, P&S" Then
          result = "32"
        ElseIf score = "Recreational Fun & Adventure" Then
          result = "31"
        Else
          result = "35"
        End If
    
        Range("AC" & a_counter).Value = result
      Next a_counter
    
    End Sub
    

    现在应该可以按预期工作了。