VBA收藏问题

时间:2015-01-21 17:44:51

标签: excel excel-vba vba

我尝试编写一个简单的VBA代码,其中组合了一些单元格值。 下面的代码问题是循环中的Cell对象不断选择整行,而不仅仅是Row集合中的一个单元

Dim Cell As Range
Dim Row As Range

Set Row = Rows(ActiveCell.Row)
Set Cell = ActiveCell

For Each Cell In Row
    With Cell
        If IsNumeric(InStr(1, Right(.Value, 1), "/")) Then
            .Value = .Value & .Offset(0, 1).Value
             .Offset(0, 1).Delete (xlShiftToLeft)
        End If
    End With
Next Cell

1 个答案:

答案 0 :(得分:0)

试试这个。对于此示例,假设有关数据在Sheet1上以及数据的起始行(stRow)和start col(testCol)。根据您的条件修改这些。

Option Explicit
Sub combine()
Dim ws As Worksheet
Dim stRow As Long, endRow As Long, testCol As Long, endCol As Long
Dim rnum As Long, cnum As Long
Dim cl As Range

Set ws = Sheets("Sheet1")
stRow = 1
testCol = 1

    With ws
        endRow = .Cells(Rows.Count, testCol).End(xlUp).Row

            For rnum = stRow To endRow
                endCol = .Cells(rnum, Columns.Count).End(xlToLeft).Column
                    For cnum = testCol To endCol - 1
                        Set cl = .Cells(rnum, cnum)
                            If Right(cl, 1) = "/" And Right(cl.Offset(0, 1), 1) <> "/" Then
                                If IsNumeric(Left(cl.Value, Len(cl.Value) - 1)) Then
                                    cl.Value = cl.Value & cl.Offset(0, 1).Value
                                    cl.Offset(0, 1).Delete (xlShiftToLeft)
                                End If
                            End If
                    Next cnum
            Next rnum
    End With
End Sub

虽然您未指定,但此代码不会合并相邻的单元格,该单元格也具有尾随&#34; /&#34;。这是基于我们不应该删除&#39; a&#39;测试&#39;值。如果不需要这种条件,则很容易改变。