在 VBA 中:我可以使用查找函数来定义一个变量,然后用于定义一个范围吗?

In VBA: Can I use a find function to define a variable that is then used to define a range?

我正在编写代码来执行一些简单的 excel 数据操作。基本上,一个名为“最终用户”的列中有空白,如果该单元格为空白,我希望它从父“外部业务部门”

中提取名称

我编写了执行此操作的代码,但问题是我收到的数据会随着时间的推移而变化,因此最终用户可能一个月在 c 列,而在另一个月在 d 列。

我当前的代码是这样的:

Sub FindColumn()
'Set ws = Sheets("group")  'sheet with data
Dim Lastrow As Long
    Lastrow = Range("B" & Rows.Count).End(xlUp).Row
'ws.Select
'Dim xyz As Range
Dim rngaddress As Range

Set rngaddress = Range("A1:Z1").Find("End User", , , xlWhole)
If rngaddress Is Nothing Then
    MsgBox "End User column was not found."
   Exit Sub
    End If
    Range(rngaddress, rngaddress).Select
    ActiveCell.EntireColumn.Insert
    ActiveCell.Value = "Final End User"
    ActiveCell.Offset(0, 1).Select
    ActiveCell.Value = ""
'Set xyz = Range("A1:Z1").Find("Final End User").Offset(1, 0)'
 'Range("xyz" & Lastrow) = "=IF(d2="""",b2,d2)"
Range("C2") = "=IF(d2="""",b2,d2)": Range("C2:C" & Lastrow).FillDown

我成功地使用带有变量的 fine 函数来定位特定单元格,但我很难将它用于 select 到最后一行的范围。我不确定是不是因为这需要两个变量,或者我只是语法错误。我不是 我试图使用 xyz 代替 C2 数据,但它不起作用(已注释掉)。有什么方法可以做到这一点,这样我就不必使用单元格地址,而是可以使用查找函数,将该信息存储在一个变量中,并以这种方式定义范围?

示例数据集为

两列,一列称为外部业务单位,一列称为最终用户。外部业务单位总是有一个名称,最终用户是随机空白。创建一个名为最终用户的列,其中的空白用相应的外部业务单位值填充。

谢谢大本钟。使用调整大小命令有效:

Set xyz = Range("A1:Z1").Find("Final End User").Offset(1, 0)
xyz.Resize(Lastrow) = "=IF(d2="""",b2,d2)"

一旦他们指出这是我使用变量的方式的问题,我也得到了使用此方法工作的代码。

Range(xyz, xyz) = "=IF(d2="""",b2,d2)"
Range(xyz, xyz).Select
Selection.AutoFill Destination:=Range(Range(ActiveCell.Address), Cells(Lastrow, ActiveCell.Column))

现在我将尝试为 if 函数使用变量。

插入列并填空

代码

Option Explicit

Sub findColumn()
    
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("group")  'sheet with data
    
    Dim eb As Range
    Set eb = ws.Rows(1).Find("External Business Unit", _
        LookIn:=xlFormulas, LookAt:=xlWhole)
    
    If eb Is Nothing Then
        MsgBox "External Business Unit column was not found."
    Else
        
        Dim LastRow As Long
        LastRow = ws.Cells(ws.Rows.Count, eb.Column).End(xlUp).Row
        Dim eu As Range
        Set eu = ws.Rows(1).Find(What:="End User", _
            LookIn:=xlFormulas, LookAt:=xlWhole)
        
        If eu Is Nothing Then
            MsgBox "End User column was not found."
        Else
            eu.EntireColumn.Insert
            ' Get the column strings only now, because 'euCol'
            ' has surely shifted, but 'ebCol' might have also.
            Dim ebCol As String
            ebCol = Split(eb.Address, "$")(1)
            Dim euCol As String
            euCol = Split(eu.Address, "$")(1)
            eu.Offset(, -1).Value = "Final End User"
            eu.Offset(1, -1).Resize(LastRow - 1).Formula _
                = "=IF(" & euCol & "2=""""," & ebCol & "2," & euCol & "2)"
        End If
    
    End If

End Sub