VBA中的With Block中有超过1个Cell范围

时间:2016-10-10 09:57:57

标签: excel vba excel-vba

简单的问题。我必须在两个不同的列中转换数据,并且所使用的代码对于两列都是相同的,所以不是两次编写代码,我只需将它们加在一起"?

这是我在另一位SO大师的帮助下写的:

With .Cells(i, 3) And .Cells(i, 5)
        .HorizontalAlignment = xlRight
        Select Case .Value
            Case Is > 1000000
                .Value = .Value / 1000000 & "Mb"
            Case Is > 1000
                .Value = .Value / 1000 & "kb"
            Case Is > 1
                .Value = .Value & "b"
            Case Else
                .Value = 0
        End Select
    End With

我添加了And .Cells(i,5)部分,但我收到了对象引用错误?

1 个答案:

答案 0 :(得分:2)

将它放在主程序中(使用好的工作表对象而不是wS):

With wS
    Alignment_And_Bytes .Cells(i, 3)
    Alignment_And_Bytes .Cells(i, 5)
End With

您可以重复使用的例程(例如,在模块的底部);)

Public Sub Alignment_And_Bytes(aCell As Range)
    If aCell.Cells.Count > 1 Then Exit Sub
    With aCell
        .HorizontalAlignment = xlRight
        Select Case .Value
            Case Is > 1000000
                .Value = .Value / 1000000 & "Mb"
            Case Is > 1000
                .Value = .Value / 1000 & "kb"
            Case Is > 1
                .Value = .Value & "b"
            Case Else
                .Value = 0
        End Select
    End With
End Sub