請問一下大大,想寫指定A5:A30將內容複製往右邊選擇性貼上值,如果爛位有已經有值則在往右移動
僅供參考
'定義範圍 rng
Sub CopyPasteValues()
Dim rng As Range
Set rng = Range("A5:A30")
'迴圈檢查每一個格子
For Each cell In rng
    '如果下一格是空的
    If IsEmpty(cell.Offset(0, 1)) Then
        '複製此格內容
        cell.Copy
        '將內容貼上到下一格
        cell.Offset(0, 1).PasteSpecial xlPasteValues
    '如果下一格不是空的
    Else
        '往右檢查30格,找到第一個空的格子
        For i = 1 To 30
            If IsEmpty(cell.Offset(0, i)) Then
                '複製此格內容
                cell.Copy
                '將內容貼上到空的格子
                cell.Offset(0, i).PasteSpecial xlPasteValues
                '跳出迴圈
                Exit For
            End If
        Next i
    End If
Next cell
End Sub
                    Range("A5:A30").Select
    Selection.Copy
    Selection.End(xlToRight).Select
    ActiveCell.Offset(columnOffset:=1).Activate
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
複製A5:A30,向右到有內容的最後一個,在向右一格,貼上值
這是一個簡單的例子,下面是一個示例,說明如何在 Microsoft Excel 中的 VBA 中執行此操作:
Sub CopyAndPasteValues()
    Dim sourceRange As Range
    Dim targetCell As Range
    Dim i As Integer
    ' Define the source range
    Set sourceRange = Range("A5:A30")
    ' Loop through each cell in the source range
    For Each targetCell In sourceRange.Cells
        ' Start copying the value to the right
        i = 1
        Do Until targetCell.Offset(0, i).Value <> ""
            i = i + 1
        Loop
        ' Copy the value to the right, starting from the first empty cell
        targetCell.Resize(1, 1).Copy
        targetCell.Offset(0, i).PasteSpecial Paste:=xlPasteValues
    Next targetCell
End Sub
此代碼定義了一個從 A5:A30 開始的源區域,並循環遍歷該區域中的每個單元格。對於每個單元格,它將值複製到右側,直到找到一個空單元格。然後用該值填充空單元格。這會將值複製並粘貼到右側,跳過任何已包含值的單元格。