对于列范围表

时间:2016-06-16 16:52:36

标签: excel excel-vba range vba

我需要帮助修复我的代码并添加单元格范围。

如果拼写错误,我试图将单元格中的值更改为正确的值。但是会添加表格,所以我需要使它成为一个灵活的代码。代码当前在开头的子站点停止,错误代码为424.我对VBA很新,而且卡住了。

Sub Consolidates()
 Dim datasheet As Worksheet

Set datasheet = ThisWorkbook.Sheets("sheet1")

lr = datasheet.Cells(Rows.Count, 9).End(xlUp).Row
For x = 2 To lr


If cell.Value = "B" Or "BR" Or " Then
cell.Value = "BR"
   ElseIf cell.Value = "CL" Or "CR" _
        Then cell.Value = "CR"
                ElseIf cell.Value = "" Then
                End If
                Next x
End Sub

2 个答案:

答案 0 :(得分:0)

Cell需要引用哪个单元格。你也不能使用那样的或语句。下面是一个简单的方法来完成它。

For x = 1 To lr
    If Cells(x, 9).Value = "B" Or Cells(x, 9).Value = "BR" Then
        Cells(x, 9).Value = "BR"         
    ElseIf Cells(x, 9).Value = "CL" Or Cells(x, 9).Value = "CR" Then
        Cells(x, 9).Value = "CR"
    End If
Next x

您应该考虑选择陈述

For x = 1 To lr
    Select Case Cells(x, 9).Value
        Case "B", "BR"
            Cells(x, 9).Value = "BR"
        Case "CL", "CR"
            Cells(x, 9).Value = "CR"
    End Select
Next x

由于区分大小写,您可以添加一个可以节省一些时间的Lcase

For x = 1 To lr
    Select Case LCase(Cells(x, 9).Value)
        Case "b", "br"
            Cells(x, 9).Value = "BR"
        Case "cl", "cr"
            Cells(x, 9).Value = "CR"
    End Select
Next x

答案 1 :(得分:0)

您可以使用以下内容

Option Explicit

Sub Consolidates()
    Dim stringsToSearch As String, stringToSubstitute As String
    Dim stringsToSearchArr As Variant, stringToSubstituteArr As Variant

    ' here define the "table"
    stringsToSearch = "B,CL" '<--| type here the strings to be searched for
    stringToSubstitute = "BR,CR" '<--| type here the corresponding strings to change searched ones into

    stringsToSearchArr = Split(stringsToSearch, ",") '<--| turn "stringsToSearch" into an array
    stringToSubstituteArr = Split(stringToSubstitute, ",") '<--| turn "stringToSubstitute" into an array

    With ThisWorkbook.Sheets("sheetTest") '<--| change "sheetTest" with your actual sheet name
        With .Range("I2:I" & .Cells(.Rows.Count, 9).End(xlUp).Row) '<--| consider all cells in column "I" from row 2 to last non empty one
            For i = LBound(stringsToSearchArr) To UBound(stringsToSearchArr) '<--| loop through the "table"
                .Replace What:=stringsToSearchArr(i), Replacement:=stringToSubstituteArr(i), LookAt:=xlWhole, MatchCase:=True '<--| find current string and replace it with its corresponding replacement
            Next i
        End With
    End With
End Sub