用vba中的列替换文本标记

时间:2016-09-13 15:55:16

标签: excel vba excel-vba

我正在尝试将文本标记替换为在列中排序的某些文本。

enter image description here

Tried...列中,我使用以下RandCell函数从一系列单元格中获取随机单元格:

Function RandCell(Rg As range, columnRange As range, headerRange As range) As Variant
    'Dim rplc
    Dim textRange

    'get random cell
    RandCell = Rg.Cells(Int(Rnd * Rg.Cells.Count) + 1)
    'find column to replace
'    rplc = RandCell.Find(headerRange)

End Function

Wanted列中,我使用以下公式来substitute值:=IF(COUNTIF(E3;"*"&$C$2&"*");SUBSTITUTE(E3;$C$2;C3);SUBSTITUTE(E3;$D$2;D3))

但是,如果我有超过10行,这个解决方案非常尴尬。因此,我正在考虑在vba中实现一个函数。

如上所述,我尝试将功能实现到RandCell功能中。但是,我对vba非常陌生,请您提出意见!

感谢您的回复!

更新

下面你可以看到一个例子。:

enter image description here

首先,选择随机文本。然后,例如在E3中,随机文字中的文字标记将替换为CD中的值。

1 个答案:

答案 0 :(得分:1)

使用以下数据:

enter image description here

在cols A B D 中,以下宏:

Sub mrquad()
    Dim L As Long, M As Long, N As Long, Kount As Long
    Dim v1F As String, v1L As String

    Kount = 10

    With Application.WorksheetFunction
        L = .CountA(Range("A:A")) - 1
        M = .CountA(Range("C:C")) - 1
        N = .CountA(Range("D:D")) - 1
        For kk = 1 To Kount
            v1 = Cells(.RandBetween(3, L + 2), "A").Value
            v1F = Left(v1, Len(v1) - 3)
            v1L = Right(v1, 3)
            If v1L = "[1]" Then
                v2 = Cells(.RandBetween(3, M + 2), "C").Value
            Else
                v2 = Cells(.RandBetween(3, N + 2), "d").Value
            End If
            Cells(kk, "F").Value = v1F & v2
        Next kk
    End With
End Sub

将从 A 列中随机选择 10 样本,并根据后缀从任一列中选择一个随机替换后缀 C 或列 D 并将结果放在 F 列中:

enter image description here

样本数由Kount变量确定。 cols C D 中的空格是单个空格而不是空。