引用列中的特定单元格

时间:2014-05-05 13:44:01

标签: excel vba excel-vba

我正在尝试在VBA中编写一个函数,它可以查看传入的一些参数,然后引用该行上的某个列。为了解释一下,如果我尝试在单元格E1中使用该函数,我想要它说A1 = 1然后返回B1 + C1,否则返回B1 + D1。

如果我将这个函数放在单元格E2中,除了第2行之外它会做同样的事情。我理解如何使用普通的excel公式做到这一点但如果我这样做会变得非常混乱。

有人可以协助我如何写这篇文章吗?

谢谢,

克雷格

2 个答案:

答案 0 :(得分:0)

我知道您要求提供VBA解决方案,但如果我理解您的问题,我强烈建议您使用以下公式:

=B1+IF(A1=1,C1,D1)

既然你说你认为常规公式会很混乱,我会试图弄清楚你还有什么其他的尝试,而你却没有明确说过。例如,如果您要求A1的值等于行号,则可以使用以下公式:

=B1+IF(A1=ROW(),C1,D1)

答案 1 :(得分:0)

编写一个函数,并使用函数调用单元格的行/列值来定义要在公式中使用的一些范围对象。

Public Function MyFunction()
Dim r as Long, c As Long
Dim myRange as Range
Dim ret
Dim msg
Set myRange = Application.Caller
r = myRange.Row
c = myRange.Column

msg = "Formula called from: " & myRange.Address

msg = msg & vbCRLF & "The first cell in this row = " & Cells(r, 1).Address

'Alternatively:

msg = msg & vbCRLF &  MsgBox "(Alternatively) " myRange.EntireRow.Cells(1).Address

'## You can also use the OFFSET method to return relative references:

msg = msg & vbCRLF & "Two cells to the left =" & myRange.Offset(0, -2).Address

MsgBox msg, vbInformation

'## Evaluate your example formula:
'   Example does NOT use relative reference and assumes that you
'   Always want to return the function from columns A/B/C/D per
'   your example =IF(A1=1,B1+C1,B1+D1)

If Cells(r, 1) = 1 Then

    ret = Cells(r, 2) + Cells(r, 3)

Else

    ret = Cells(r, 2) + Cells(r, 4)

End If

'return the value to the function:
MyFunction = ret

End Function
相关问题