VBA:基于列标题的偏移量

时间:2017-11-27 12:59:22

标签: excel vba excel-vba

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

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

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

并且列N被命名为“country”,我不想写:

offset(,12).value = ...

相反,如果有这样的话:

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

我要求这样做的原因是没有具体的偏移号,以使代码对我的Excel工作表可能发生的任何更改更具弹性。

我希望解释清楚。谢谢!

2 个答案:

答案 0 :(得分:1)

尝试下面的功能,会将Offset所需的列数从Rng返回到"标题"你在寻找。

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

测试子代码(以测试上述功能):

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    

答案 1 :(得分:0)

我需要从定义为范围的行中获取列值。

Public Function ProcessOneLine(row As Range) As String

这对我有用

row.Offset(0,2).Value2 ' returns the value in Column 3
row.Offset(1,Range("C1").Column).Value2 ' also returns the value in Column 

所以使用这样的东西:

Dim srcColumn as String
Dim colPosn as Integer
srcColumn = "C"
colPosn = Range(srcColumn & "1").Column
cellValue = row.Offset(0,colPosn-1).Value2