结合 VBA 和复制粘贴

结合 VBA 和复制粘贴

我想知道是否有人可以帮助我。

当在“B”列中输入值时,我使用下面的代码自动填充具有预定义文本的多个列。

Option Explicit
Public preValue As Variant


    Private Sub Worksheet_Change(ByVal Target As Range)

        Dim cell As Range, res As Variant
        Dim FirstBlankCell As Range
        Dim lr As Long
        Dim msg
        Dim rCell As Range
        Dim Rng As Range, Dn As Range
        Dim Rng1 As Range
        Dim Rng2 As Range
        Dim Rng3 As Range
        Dim Rng4 As Range
        Dim Rw As Range


        If Target.Cells.Count > 1 Then Exit Sub

        lr = lr


        With Target
            Select Case True

            Case .Column = 2
            If .Value2 > 0 And .Value2 <> "Enter your name" And .Offset(, -1) = "" Then
                    .Offset(, 1).Value2 = "Yes"
                    .Offset(, 2).Value2 = "--Select--"
                    .Offset(, 3).Value2 = "--Select--"
                    .Offset(, 4).Value2 = "--Select--"
                    .Offset(, 5).Value2 = "Enter your FTE"
                    .Offset(, 6).Value2 = "C&R"
                    .Offset(, 7).Value2 = "--Select--"
                    .Offset(, 17).Value2 = "Enter the name of your Line Manager"
                  End If
            Case Else
            End Select
        End With

    End Sub

这很好,但我现在想进一步扩展此功能。除了手动输入值外,我还希望在将值复制并粘贴到“B”列时填充列。

当我将现有工作表中的信息迁移到我正在构建的新工作表中时,这将有所帮助。虽然这是我需要做的最后一个更改,但事实证明,找到解决方案是最困难的。

我只是想知道是否有人可以看看这个问题并提供一些关于如何实现这一目标的指导。

非常感谢并致以亲切的问候

克里斯

答案1

根据 Karen 的说法,如果内容被剪切和粘贴,该事件就会触发。问题是,您发布的代码会检查返回的单元格数量是否大于 1,如果是,它会停止执行事件:

If Target.Cells.Count > 1 Then Exit Sub

将代码改为这样,它就应该可以正常工作。

Dim cell As Range, res As Variant
Dim FirstBlankCell As Range
Dim lr As Long
Dim msg
Dim rCell As Range
Dim Rng As Range, Dn As Range
Dim Rng1 As Range
Dim Rng2 As Range
Dim Rng3 As Range
Dim Rng4 As Range
Dim Rw As Range

lr = lr

Dim r As Range
For Each r In Target.Cells
With r
    Select Case True

    Case .Column = 2
    If .Value2 > 0 And .Value2 <> "Enter your name" And .Offset(, -1) = "" Then
            .Offset(, 1).Value2 = "Yes"
            .Offset(, 2).Value2 = "--Select--"
            .Offset(, 3).Value2 = "--Select--"
            .Offset(, 4).Value2 = "--Select--"
            .Offset(, 5).Value2 = "Enter your FTE"
            .Offset(, 6).Value2 = "C&R"
            .Offset(, 7).Value2 = "--Select--"
            .Offset(, 17).Value2 = "Enter the name of your Line Manager"
          End If
    Case Else
        End Select
    End With
Next r

这里所做的是删除了代码行,以允许即使目标范围内有多个单元格也可以触发事件,然后我们对目标中包含的单元格使用 For Each 循环来处理每一行。

尼姆

答案2

工作表_更改(ByVal 目标作为范围)事件由两个都手动输入和粘贴数据,所以它应该可以正常工作。你试过了吗?

相关内容