如何交换单元格中的值

时间:2018-10-21 02:08:36

标签: vba excel-vba

因此,我试图在彼此相邻的单元格中交换值,盯着G2单元格,并在向右移动时继续执行此操作,直到在行中找到一个空单元格为止。然后,向下移动一行,然后向右移动,直到找到一个空白单元格为止。然后向下移动,依此类推。棘手的是,列的变化​​很大,从大约20到超过3000。一切都始于单元格G2,在这种情况下,它下降到G100,但随时可能改变。到目前为止,我可以找到最右边的列并设置循环范围,但是循环本身已关闭,因此无法正常工作。有什么想法吗,专家?

Here is the code sample that I am testing.

Dim LastColumn As Long
With ActiveSheet.UsedRange
    LastColumn = .Columns(.Columns.Count).Column
End With

Dim ColumnNumber As Long
Dim ColumnLetter As String
ColumnLetter = Split(Cells(1, LastColumn).Address, "$")(1)

    Columns("G:" & ColumnLetter).Select
    Selection.Replace What:="name: ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:="- data_type: ", Replacement:="", LookAt:=xlPart _
        , SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

' start to swap cell contents...
Dim r As Range
Dim c As Range
Dim sht As Worksheet
Dim LastRow As Long
Dim temp As Double

Set sht = ActiveSheet
LastRow = sht.Cells(sht.Rows.Count, "G").End(xlUp).Row

Set r = Range("G2:" & ColumnLetter & LastRow)

For Each c In r
    c.Select
    temp = ActiveCell.Value
    ActiveCell.Offset(0, 1).Value = ActiveCell.Offset(0, 1).Value & ":" & temp
    ActiveCell.Offset(0, 2).Select
Next

1 个答案:

答案 0 :(得分:3)

用数字浏览列,并使用一些基本数学运算来确定源和目的地。

Option Explicit

Sub consolidate()
    Dim r As Long, c As Long, d As Long

    With Worksheets(ActiveSheet.Name)
        For r = 2 To .Cells(.Rows.Count, "G").End(xlUp).Row
            d = 7
            For c = 7 To .Cells(r, .Columns.Count).End(xlToLeft).Column Step 2
                .Cells(r, d) = Join(Array(.Cells(r, c).Value, _
                                          .Cells(r, c + 1).Value), Chr(32))
                 d = d + 1
            Next c
            .Range(.Cells(r, d), .Cells(r, .Columns.Count).End(xlToLeft)).Clear
        Next r
    End With
End Sub