将variables设置为标题文本列

我有一个工作簿,从来没有收到相同的格式。 为了防止人工干预,我需要捕获文本employee所在的列。例如,如果文本在列O中 – 我将执行下面的操作,但是我需要Cells(i,"O")为根据包含文本employee的单元格进行更改

 Sub DoThis() Application.ScreenUpdating = False Dim i As Long For i = Range("A" & Rows.Count).End(3).Row To 2 Step -1 If Not IsEmpty(Cells(i, "O").Value) Then 'stuff here End If Next i End Sub 

您可以使用“ Find方法并获取在“单元格”中使用的employee所在单元格的列:

 Option Explicit Sub DoThis() Dim i As Long Dim lngCol As Long With Worksheets("Sheet1") '<-- change to your sheet lngCol = .Rows(1).Find("employee").Column '<-- assumes header in Row 1 For i = .Range("A" & .Rows.Count).End(3).Row To 2 Step -1 If Not IsEmpty(.Cells(i, lngCol).Value) Then 'stuff here End If Next i End With End Sub 

使用find方法

 Cells.Find("employee") 

这将find指定范围内的单元格(在这里,我使用了Cells但是将其缩小到您的范围),它将返回包含文本“employee”的单元格。 然后,您可以将其作为Range对象引用,即使用.Row获取行号或.Column获取列号