简体   繁体   English

如何在VBA中实现Excel公式

[英]How to implement Excel formulas in vba

I am programming a tool now by VBA and I have got a problem with writing a IF formula. 我现在正在使用VBA编程工具,但编写IF公式时遇到问题。 I have two worksheets "site" and "overview", I would like to write an IF formula for the "site" worksheet range column L. 我有两个工作表“站点”和“概述”,我想为“站点”工作表范围列L编写一个IF公式。

In the Excel formula bar it is the following formula 在Excel公式栏中,它是以下公式

=IF(ISBLANK('Overview'!$Q$2:$Q$17), 'Site'L2:L17, 'Overview',Q2:Q17)

How should I write and implement this formula with a correct syntax in VBA. 如何在VBA中使用正确的语法编写和实现此公式。 Thanks in advance. 提前致谢。

For your formula, it is unclear which cells it is in. It cannot be in "Site" column L or "Overview" column Q, as your question suggests, because then you would have a circular reference. 对于您的公式,目前尚不清楚它位于哪个单元格中。正如您的问题所建议的那样,它不能位于“站点”列L或“概述”列Q中,因为那样您将有一个循环引用。 I'm going to assume it's in "Overview" column L. 我将假定它在“概述”列L中。

Now to use the VBA If logic. 现在使用VBA If逻辑。

' Shorthand "With" to prefix "Sheets" with a dot "." means always reference this workbook
With ThisWorkbook

Dim vcell as Range
For Each vcell in .Sheets("Overview").Range("L2:L17")

    ' Check if column Q cell on same row is blank
    If .Sheets("Overview").Range("Q" & vcell.row).Text = "" then

        ' Value if vcell is blank
        vcell.Value = .Sheets("Site").Range("L" & vcell.row).value

    Else

        ' Value if vcell is not blank
        vcell.Value = .Sheets("Overview").Range("Q" & vcell.row).value            

    End If

End With

If you're used to writing formulae in Excel cells but not in VBA, you may find use for the WorksheetFunction ability of VBA: MSDN Worksheet Function Documentation . 如果您习惯于在Excel单元格中而不是在VBA中编写公式,则可能会发现它可用于VBA的WorksheetFunction功能MSDN Worksheet Function Documentation However, you're better off here using the native If logic for its added power and versatility, which is why there is no Worksheet Function for If . 但是,最好在这里使用本机If逻辑,以增强功能和多功能性,这就是为什么If没有Worksheet Function的原因。

Also take care copying cell formulae into the Worksheet Function sections of code. 还请注意将单元格公式复制到代码的“工作表功能”部分。 Your quotations around the sheet names would cause problems. 您在工作表名称周围的引用会引起问题。 I mention this because in VBA, the apostrophe ' will start a comment, and so the code will be ignored! 我之所以这样说是因为在VBA中,撇号'将开始注释,因此代码将被忽略!

You can use an "Immediate If" for this type of thing but please make sure you fully understand the potential pitfalls of this syntax: 您可以对这种类型的事件使用“立即If”,但请确保您完全了解此语法的潜在陷阱:

https://support.office.com/en-gb/article/IIf-Function-32436ecf-c629-48a3-9900-647539c764e3 https://support.office.com/en-gb/article/IIf-Function-32436ecf-c629-48a3-9900-647539c764e3

Like so: 像这样:

Set myRange = IIf([ISBLANK(Overview!$Q$2:$Q$17)], Sheets("site").Range(L2:L17), Sheets("Overview").Range("Q2:Q17"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM