如何在excel VBA中相对引用单元格

时间:2015-01-26 17:26:20

标签: excel-vba vba excel

我在excel 2013工作表中有一个quicktable(带有可以过滤的标题的表格)。 在vba中,我知道如何通过使用像Cells这样的东西来获取单元格的值(ActiveCell.Row,12).Value 但是如果我想在具有特定名称的列下获取活动行的单元格,例如" CUSTOMER NAME"标题。不是列A,B或C,或1,2或3,而是列的自描述名称。可能吗?推理 - 如果我稍后将此列重新定位到表中的不同顺序,则引用在VBA中仍然是正确的。

4 个答案:

答案 0 :(得分:0)

Sub test()
Dim lstObj As ListObject
Dim rColumn As Range

' Get the table reference
Set lstObj = Worksheets("Sheet1").ListObjects("Table1")

' Get the column reference
Set rColumn = lstObj.ListColumns("Field1").DataBodyRange

' display first data value in the column
MsgBox rColumn(1).Value

End Sub

答案 1 :(得分:0)

确保您的数据位于表格中并在工作簿中设置命名范围,然后您可以将这些数据引用到vba中的范围,如下所示:

     MyWorksheet.Range("MyNamedRange").Rows(ActiveCell.Row)

答案 2 :(得分:0)

如果你的范围只有1个单元格,那么MyWorksheet.Range("MyNamedRange")对我有效。

答案 3 :(得分:0)

我个人喜欢使用Range.Find()方法来动态搜索列。这允许您避免使用ListObjects(尽管我总是将我的数据格式化为ListObjects用于其他目的)。以下代码允许您快速,动态地查找指定的列:

Sub DynamicColumn()
Dim r As Range                              ' Stores the range to find
Dim ws As Worksheet                         ' Stores the current ws

Dim iColumn As Integer                      ' Variable to store the column #.


' I use "ThisWorkbook" to qualify all of my worksheet references, or I set a
' workbook variable to "ThisWorkbook". This just helps prevent accidental references
' to other workbooks.

Set ws = ThisWorkbook.Sheets("SheetName")

' Search the worksheet for "TextToFind" and assign it to the r variable.
' There are additional arguments for the find method that you can find on MSDN.


Set r = ws.Cells.Find("TextToFind")


' If you only want to search in the (x) row, use this version.
' Set r = ws.Rows(x).Find("AlternativeSearch")

' Get the column number of your header.

' The "Is Not" "Is Nothing" statement tripped me up for a while. Basically,
' when we "Not" r, we are flipping it. If it contains a value it becomes
' nothing, if it doesn't contain a value then it skips the statement without
' raising an error.

If Not r Is Nothing Then iColumn = r.Column

End Sub

然后将您的列号存储在iColumn变量中。您也可以参考“r.Column”并使用范围变量的其他方法。

我希望这有帮助!