简体   繁体   English

根据条件将单元格复制并粘贴到下一列

[英]Copy and paste cell to the next column based on a condition

I am trying to paste the cell contents based on a condition that if there is no match then copy the first word of the cell and paste it to the next cell to the right but it gives me object not defined error. 我正在尝试根据以下条件粘贴单元格内容:如果没有匹配项,则复制该单元格的第一个单词,然后将其粘贴到右侧的下一个单元格中,但这会给我对象未定义的错误。

CENTRUM ADVANCE TABLET should copy only CENTRUM CENTRUM ADVANCE平板电脑应仅复制CENTRUM

Below is my code 下面是我的代码

Sub splitUpRegexPattern()

Dim re As Object, c As Range
Dim allMatches
Dim cell As Object
Dim count As Integer
count = 0

For Each cell In Selection
    count = count + 1
Next cell
' MsgBox count & " item(s) selected"

Set re = CreateObject("VBScript.RegExp")
re.Pattern = "((\d+(?:\.\d+)?)\s*(m?g|mcg|ml|IU|MIU|mgs|µg|gm|microg|microgram)\b)"
re.IgnoreCase = True
re.Global = True

For Each c In ActiveSheet.Range("D2", ActiveSheet.Range("D2").End(xlDown)).Cells ' Select the range and run the code
    Set allMatches = re.Execute(c.Value)
    If allMatches.count > 0 Then
        c.Offset(0, 1).Value = allMatches(0)
    Else
        Selection.Copy
        c.Offset(0, 1).Value.Paste
    End If
Next c
End Sub

A couple changes I believe you need to make: 我相信您需要进行一些更改:

c.Copy
c.Offset(0, 1).PasteSpecial

There's no paste property of a value. 没有值的粘贴属性。 c is a Range so it has Copy and Paste methods. c是一个范围,因此具有复制和粘贴方法。

For your other question: 对于您的其他问题:

Dim LArray() As String
LArray = Split(c.Text, " ")
c.Offset(0, 1).Item(1, 1).Value = LArray(0)

Work with split function, Example 使用分割功能,示例

Set allMatches = re.Execute(c.Value)
If allMatches.count > 0 Then
    c.Offset(0, 1).Value = allMatches(0)
Else
    c.Offset(0, 1).Value = Split(c.Value, " ")(0)
End If

Split Function (Visual Basic) 拆分功能(Visual Basic)

Split (text_string, delimiter, limit, compare)

text_string: Would be C.Value . text_string: C.Value

delimiter: delimiter would be space character (" "). delimiter: 定界符将为空格字符(“”)。

limit: leave the limit argument blank because we need to separate out all the words from C.Value . limit: limit参数保留为空白,因为我们需要从C.Value分离出所有单词。

compare: This would be blank, as blank specifies binary comparison method. compare: 这将是空白,因为空白指定二进制比较方法。

Try something like this 试试这个

Else
    Selection.Copy
    Selection.Offset(1, 0).Select
    ActiveSheet.Paste
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM