VBA:基于列标题的偏移量

是否有可能偏移到基于列标题的单元格右侧? 我有一些循环遍历范围的代码,如果它发现一个特定的值,它将偏移12列向右。 而不是说偏​​移(,12),有没有一种方法,我可以说在同一行右边偏移到我想要的标题列?

例如,如果列B被命名为“主机”,我的范围是

rng = ws.range("B1:B20") 

N列为“国家”,我不想写:

 offset(,12).value = ... 

相反,如果有像这样的东西:

 offset(to column: country).value =... 

我问这个问题的原因是没有指定一个偏移数字,以使代码更有弹性,可能发生在我的Excel工作表中的任何变化。

我希望解释清楚。 谢谢!

尝试下面的函数,将返回您需要从您的Rng Offset到您正在寻找的“标题”列的数量。

 Option Explicit Function OffesttoHeader(CurrentCol As Long, FindRng As Range, HeaderStr As String) As Long Dim HeaderRng As Range Set HeaderRng = FindRng.Find(what:=HeaderStr) If Not HeaderRng Is Nothing Then OffesttoHeader = HeaderRng.Column - CurrentCol + 1 Else OffesttoHeader = -10000 ' raise to a large value >> as an error End If End Function 

testing子代码 (testing上述function):

 Sub Test() Dim ws As Worksheet Dim Rng As Range Dim NumberofCols As Long Set ws = ThisWorkbook.Sheets("Sheet1") ' modify to your sheet's name Set Rng = ws.Range("B1:B20") ' pass the following parameters: ' 1. Rng.column - in your case column B = 2 ' 2. ws.Rows(1) - the Range to search for the Header, first row in ws worksheet ' 3. "Header" - the Header string you are searching for NumberofCols = OffesttoHeader(Rng.Column, ws.Rows(1), "Header") ' raise an error message box If NumberofCols = -10000 Then MsgBox "Unable to find Header" End If End Sub 

为了获得上面find的解决scheme,使用Range.Find方法。

 'Column Number Dim clmCountry as Integer 

从这里,我们想通过使用Range.Find方法find头

 'to find the header With ThisWorkbook.Sheets("SheetName") 'update the range if necessary clmCountry = .Range("A1:Z1").Find("HeaderName").Column End With 

一旦你find了所需的栏目,你可以通过以下方式来抵消:

 ... Offset(RowNum, clmCountry).Value = ...