【问题标题】:Find and Replace Certain Values w/ VBA [closed]使用 VBA 查找和替换某些值 [关闭]
【发布时间】:2022-01-04 06:29:24
【问题描述】:

我是 VBA 新手,但我希望有人能帮助我。 我想在 Sheet1 (Col.A) 中找到 Img1.(从 I8 到 K10) 的值,这是不同用户的列表,并将 Col.F 中的相应值替换为 1。

我正在尝试使用 Vba 来实现,但我不知道如何编写代码。

图1。我想在工作表 1 中找到的值

图2。在 Img1 中找到给定用户并将 Col.F 的值更改为 1

【问题讨论】:

  • 我正在尝试在 Excel 中使用 VBA,但我不知道要编写什么代码

标签: excel vba replace find


【解决方案1】:

你可以试试下面我的代码。您需要更新表格、工作表和范围名称以适合您的示例。

Sub findvalues()
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With

    Dim dict As Object
    Dim dict2 As Object
    Dim anArr As Variant
    Dim r As Range
    Dim r2 As Range
    Dim rC As Range
    Dim nRc As Range
    
    Set r = Sheets(3).Range("I8:K10")
    Set nRc = Sheets(3).ListObjects("Table1").ListColumns(1).Range
     
     Set dict = CreateObject("Scripting.Dictionary")
    
    For Each rC In r
            If rC.Value <> "" Then
                    On Error Resume Next
                       dict.Add rC.Value, 1
                End If
                 On Error GoTo 0
    Next rC
     
     Set dict2 = CreateObject("Scripting.Dictionary")
    
    For Each rC2 In nRc
            If rC2.Value <> "" Then
            IsInArray = Not IsError(Application.match(rC2.Value, dict.keys(), 0))
                If IsInArray = True Then
                    On Error Resume Next
                       dict2.Add rC2.Address, 1
                End If
                 On Error GoTo 0
            End If
    Next rC2
    
    anArr = Join(dict2.keys(), ",")
    anArr = Replace(anArr, "$", "")
    
    If Len(anArr) > 253 Then
        For Each it In dict2.keys()
                    ThisWorkbook.Sheets(3).Range(it).Offset(, 5) = 1
        Next it
        Else
        Sheets(3).Range(anArr).Offset(, 5) = 1
    End If

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With
end sub

编辑:

如果您对使用On Error Resume Next 不感兴趣,您可以根据自己的目的编辑下面的代码

With CreateObject("scripting.dictionary")
  For Each it In Array("aa1", "aa2", "aa1", "aa3", "aa4", "aa2")
    If Not .Exists(it) Then .Add it, it & "_content"
  Next
End With

Edit2:上面代码的最大问题是没有考虑 .range() 的 255 个字符限制。所以,我在上面的代码中创建了一个解决方法。在大约 8K 行上,它运行了 0.4 秒。

【讨论】:

  • 请注意 Dim r, r2, rC, nRc As Range 仅声明 nRc As Range 而其他所有声明为 Variant。在 VBA 中,您需要为 每个 变量 Dim r As Range, r2 As Range, rC As Range, nRc As Range 指定类型,否则默认为 Variant! • Dim dict, dict2 As Object 相同。
  • 很高兴知道。我会记住这一点的。
  • 我建议使用dict.Exists 而不是On Error Resume Next。遇到错误异常(并捕获它)会带来更高的成本,然后检查值的存在。如果可能,最好不要使用On Error Resume Next。
  • 我确实知道,但我还没有进入 dict.exists 部分。我确实读过它,但我认为代码没有必要。
  • 我添加了它以防有人对该代码感兴趣。
猜你喜欢
  • 1970-01-01
  • 2015-12-01
  • 2023-01-25
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
相关资源
最近更新 更多