簡體   English   中英

將單元格值復制到一系列單元格

[英]Copy cell value to a range of cells

我是VBA的新手,我想在其值更改時將值從一個單元格復制到多個單元格。

A2的值在不斷變化,當發生這種情況時,我希望將該值復制到單元格C2:C21(然后最終復制到單元格D2:D21)

這是我要實現的示例:

http://i.stack.imgur.com/xJZyZ.jpg

到目前為止,我編寫了以下代碼:

Sub Worksheet_Change(ByVal Target As Range)
   For i = 0 To 19
      If Not Intersect(Target, Range("AS2")) Is Nothing Then
         Cells(Target.Row + i, 58).Value = Cells(Target.Row, 45).Value
      End If
   Next i
End Sub

但這僅將一個A2值復制到所有單元格C2至C22。

誰能幫我正確編寫此代碼?

Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("AS2")) Is Nothing Then
        For CurCol = 3 to 4
            For CurRow = 2 to 21
                If Cells(CurRow, CurCol).Value = "" Then
                    Cells(CurRow, CurCol).Value = Target.Value
                    Exit Sub
                EndIf
            Next CurRow
        Next CurCol
    End If
End Sub

我想這就是你所追求的:

Option Explicit

Sub Worksheet_Change(ByVal Target As Range)
    Dim nVals As Long

    If Not Intersect(Target, Range("A2")) Is Nothing Then
        With Range("C2:D21")
            nVals = WorksheetFunction.CountA(.Cells)
            If nVals = .Count Then Exit Sub
            Application.EnableEvents = False
            On Error GoTo exitsub
            .Cells(nVals Mod .Rows.Count + 1, IIf(nVals >= .Rows.Count, 2, 1)).Value = Target.Value
        End With
    End If

exitsub:
Application.EnableEvents = True
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM