简体   繁体   English

VBA Replace()处于类型不匹配错误的循环中

[英]VBA Replace() in a loop with type mismatch error

I'm fairly new to VBA, and I'm just trying to replace any character, "NA", "ZZ", "Z", in column "N" and "O" with "0". 我对VBA还是很陌生,我只是想将“ N”和“ O”列中的任何字符“ NA”,“ ZZ”,“ Z”替换为“ 0”。 The following is a loop with if statement, but for some reason I kept on getting 以下是带有if语句的循环,但是由于某些原因,我一直在获取

runtime 13 error with type mismatch 类型不匹配的运行时13错误

Could anyone help me to fix the error? 谁能帮我解决错误?

Thanks! 谢谢!

Dim v as String
sym = Array("NA", "ZZ", "Z")

  If Worksheets("Sheet1").Columns("N") Then
   For Each a In sym
    v = Replace(v, a, "0")
   Next a

 ElseIf Worksheets("Sheet1").Columns("O") Then
   For Each a In sym
     v = Replace(v, a, "0")
   Next a

 End If

You can do it like so. 您可以这样做。 It's good practice to specify the various parameters . 最好指定各种参数

sym = Array("NA", "ZZ", "Z")

With Worksheets("Sheet1").Range("N:O")
    For Each a In sym
        .Cells.Replace what:=a, replacement:=0
   Next a
End With

You don't need to loop over the cells, try: 您不需要遍历单元格,请尝试:

Sub lydias()
    With Sheets("Sheet1").Range("N:O")
        .Replace What:="NA", replacement:="0"
        .Replace What:="ZZ", replacement:="0"
        .Replace What:="Z", replacement:="0"
    End With
End Sub

Try this: 尝试这个:

Sub test()

Dim sym As Variant
sym = Array("NA", "ZZ", "Z")

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")

Dim colums_range As Range

With ws
Set colums_range = Union(.Columns("N").SpecialCells(xlCellTypeConstants), .Columns("O").SpecialCells(xlCellTypeConstants))
End With

   For Each element In sym

    colums_range.Replace What:=CStr(element), Replacement:="0", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
    ReplaceFormat:=False

   Next element

End Sub

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

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