【问题标题】:Excel - type mismatch error 13 in VBA when selecting multiple cellsExcel - 选择多个单元格时在 VBA 中键入不匹配错误 13
【发布时间】:2017-08-09 20:23:21
【问题描述】:

我是 VBA 新手,但遇到了一个小问题。当我只选择一个单元格时,代码工作正常。但是当我尝试选择多个单元格时,它会显示类型不匹配。 我感谢任何帮助:) 这是代码:

Sub Asterisk()
Dim Cell As Range
If Selection.Value = "<.0001" Then
    Selection.Value = 0.0001
Else
    Selection.Value = Selection.Value
        If (Selection.Value < 0.001) Then
            Selection.Value = "***"
        ElseIf (Selection.Value >= 0.001) And (Selection.Value < 0.01) Then
            Selection.Value = "**"
        ElseIf (Selection.Value >= 0.01) And (Selection.Value < 0.05) Then
            Selection.Value = "*"
        Else
            Selection.Value = "Not significant"
        End If
End If
End Sub

【问题讨论】:

  • 您需要执行 For Each 循环以遍历选择中的每个单元格。这样,无论您选择的是单个单元格还是多个单元格,它都会起作用。
  • 非常感谢!但是我该怎么做呢?
  • @tigeravatar 这应该是一个答案,而不是一个评论
  • 使用Selection.Value = Selection.Value有什么意义?

标签: vba excel type-mismatch


【解决方案1】:

根据tigeravatar 的建议,以下是您将如何使用 for each 循环遍历选择中的单元格

Sub Asterisk()
Dim Cell As Range
    For Each Cell In Selection
        If Cell.Value = "<.0001" Then
            Cell.Value = 0.0001
        Else
            Cell.Value = Cell.Value
                If (Cell.Value < 0.001) Then
                    Cell.Value = "***"
                ElseIf (Cell.Value >= 0.001) And (Cell.Value < 0.01) Then
                    Cell.Value = "**"
                ElseIf (Cell.Value >= 0.01) And (Cell.Value < 0.05) Then
                    Cell.Value = "*"
                Else
                    Cell.Value = "Not significant"
                End If
        End If
    Next Cell
End Sub

【讨论】:

  • 注意:会因 类型不匹配 或其他原因而崩溃,具体取决于 Selection 是什么(可能是从 ChartRange 的任何内容或Shape)。
  • 不要使用Selection ...直接引用单元格。例如:For Each Cell In Sheets("Sheet1").Range("a1:b7")
猜你喜欢
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多