首页 > 解决方案 > 我试图找到一个空格并在 VBA 中插入一个字符串

问题描述

我正在编写一个子程序,它将过滤数据并将名称添加到列中的空白区域。到目前为止,我已经能够编写选择和过滤数据的部分代码,但我想帮助我了解如何将字符串名称插入空白单元格,然后将其击落到列中。

我尝试了一个 if 函数,=if(cell="HEB", "HEB",0)然后将其显示在列中。我在 D 列中查看商店是否是 HEB,如果是,我想用“HEB”填充 P 列中的同一行

Sub addHEB()
    Dim sht As Worksheet
    Dim fnd As Variant
    Dim rplc As Variant

    fnd = ""
    rplc = "HEB"

    'Store a specfic sheet to a variable
    Set sht = Sheets("Sheet1")

    'Perform the Find/Replace All
    sht.Cells.Replace what:=fnd, Replacement:=rplc, _
                      LookAt:=Range.P: P , SearchOrder:=xlByRows, _
                      MatchCase:=False, SearchFormat:=False, _
                      ReplaceFormat:=False

End Sub

我预计这会在对应的空白单元格中用“HEB”填写 P 列,但它不起作用。工作表中还有其他空白,因此是否有更合乎逻辑的方法来用“HEB”填充空白列 P。

标签: excelvba

解决方案


我认为在不调用Find函数的情况下工作更简单。诀窍是限制您的范围,因为如果您搜索 D 列的所有内容,则有数百万行:

Option Explicit

Sub FillBlanksWithHEB()
    Dim sht As Worksheet
    Set sht = Sheet1

    Const lastRow As Long = 10
    Dim searchArea As Range
    Dim hebArea As Range
    Set searchArea = sht.Range("D1:D" & lastRow)
    Set hebArea = sht.Range("P1:P" & lastRow)

    Dim cell As Variant
    For Each cell In searchArea
        If IsEmpty(cell) Then
            hebArea.Cells(cell.row, 1).value = "HEB"
        End If
    Next cell
End Sub

推荐阅读