将每个子输入作为单元格更改为一系列单元格

时间:2016-05-13 18:16:51

标签: excel-vba vba excel

我想修改这个子而不是一次接受一个单元,一个从源到一个目的地,接受一系列单元,一个源范围和一个目标范围。

我的目标是调用此Sub来复制输入范围的单元格中的数据验证,并通过调用此Sub将它们粘贴到另一个单元格范围内。这个Sub意味着能够被其他Subs(也可能是函数)调用,因此它需要可重用。有人可以帮我解决这个问题吗?

我想修改的代码是:

Sub CopyValidation(ByRef rngSourceCell As Range, ByRef rngTargetCell As Range)
    With rngTargetCell.Validation
        .Delete
        .Add Type:=rngSourceCell.Validation.Type, _
            AlertStyle:=rngSourceCell.Validation.AlertStyle, _
            Operator:=rngSourceCell.Validation.Operator, Formula1:=rngSourceCell.Validation.Formula1, Formula2:=rngSourceCell.Validation.Formula2
        .ErrorMessage = rngSourceCell.Validation.ErrorMessage
        .ErrorTitle = rngSourceCell.Validation.ErrorTitle
        .IgnoreBlank = rngSourceCell.Validation.IgnoreBlank
        .IMEMode = rngSourceCell.Validation.IMEMode
        .InCellDropdown = rngSourceCell.Validation.InCellDropdown
        .InputMessage = rngSourceCell.Validation.InputMessage
        .InputTitle = rngSourceCell.Validation.InputTitle
        .ShowError = rngSourceCell.Validation.ShowError
        .ShowInput = rngSourceCell.Validation.ShowInput
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

您无需单独设置每个参数。考虑:

Sub dural()
    Dim r1 As Range, r2 As Range

    Set r1 = Range("A1:A10")
    Set r2 = Range("B1:B10")
    r1.Copy
    r2.PasteSpecial xlPasteValidation
End Sub

即使您的单细胞例程也可以使用它:

Sub CopyValidation(ByRef rngSourceCell As Range, ByRef rngTargetCell As Range)
    rngSourceCell.Copy
    rngTargetCell.PasteSpecial xlPasteValidation
End Sub

事实上,第二个例程可以处理单个单元格和多个单元格范围(只要范围是同构的)