将String设置为范围

时间:2018-04-04 15:37:33

标签: excel-vba vba excel

我有专栏S& U与姓名。在Q栏中,我有客户类型(组织为O,个人为P)。对于所有客户Q,我想比较S列和U列的前20个字符,如果它们匹配,则得到值" ok"在第五列中,我已经完成了一个代码,但它在行中给出了编译错误 - str =工作表(" ORD_CS")。范​​围(左(" S:S"), 20)。有些人可以帮我修复这段代码。感谢

Sub Macro1()
'
'Match Organization names
'

'
    Dim sht As Worksheet
    Dim LR As Long
    Dim i As Long
    Dim str As String, str1 As String

    Set sht = ActiveWorkbook.Worksheets("ORD_CS")
    LR = sht.UsedRange.Rows.Count
    str = Worksheets("ORD_CS").Range(Left("S:S"), 20)
    str1 = Worksheets("ORD_CS").Range(Left("U:U"), 20)

    With sht
            For i = 8 To LR
                If CStr(.Range("Q" & i).Value) = "O" Then
                    If str = str1 Then
                        Range("V" & i).Value = "ok"
                    End If
                End If
            Next i
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

您以错误的方式选择子字符串。你想要替换:

str = Worksheets("ORD_CS").Range(Left("S:S"), 20)
str1 = Worksheets("ORD_CS").Range(Left("U:U"), 20)

使用:

Sub Macro1()
'
'Match Organization names
'

'
    Dim sht As Worksheet
    Dim LR As Long
    Dim i As Long
    Dim str As String, str1 As String

    Set sht = ActiveWorkbook.Worksheets("ORD_CS")
    LR = sht.UsedRange.Rows.Count

    With sht
            For i = 8 To LR
                If CStr(.Range("Q" & i).Value) = "O" Then
                    str = Left(.Range("S" & i).Value, 20)
                    str1 = Left(.Range("U" & i).Value, 20)
                    If str = str1 Then
                        Range("V" & i).Value = "ok"
                    End If
                End If
            Next i
    End With
End Sub

目前,您尝试从一个范围中选择20个字符。这个字符串选择需要在循环中完成,而不是在循环开始时,除非我不理解你的问题。