简体   繁体   English

Excel VBA-基于活动单元格运行宏

[英]Excel VBA - Run macro based upon Active Cell

I'm creating an Excel macro that will filter a source worksheet based upon several criteria. 我正在创建一个Excel宏,它将根据多个条件过滤源工作表。 Basically, the macro says if you're in the Ford sheet, go to the source sheet and filter on ford. 基本上,宏会说如果您在福特表中,请转到源表并在福特上进行过滤。 That part is easy. 这部分很容易。 What I'm struggling with is telling it to filter the source sheet based upon the active cell. 我正在努力的是告诉它根据活动单元过滤源工作表。 So... 所以...

If ActiveCell is A1, go to source and perform a filter of X number of criteria, else if ActiveCell is B1, go to source and perform this other filter, and so on and so forth. 如果ActiveCell是A1,则转到源并执行X个条件的过滤器,否则,如果ActiveCell是B1,则转到源并执行此其他过滤器,依此类推。

Here's what I have so far: 这是我到目前为止的内容:

If ActiveCell = Range("C36") Then
    Sheets("Source-Cars").Select
        'Unfilter data
        Application.Goto (Sheets("Source-Cars").Range("A1"))
        If ActiveSheet.FilterMode Then 
           ActiveSheet.ShowAllData
        end if
end if

The problem here is that ActiveCell = Range("C36") is looking at the value of that cell, not whether or not I've selected the cell. 这里的问题是ActiveCell = Range(“ C36”)正在查看该单元格的值,而不是我是否已选择该单元格。 So, if I select another cell with the same value as C36, it performs the filter instead of returning the error message box I built in. 因此,如果我选择另一个与C36值相同的单元格,它将执行过滤器,而不是返回我内置的错误消息框。

Thoughts on how to run the logic based upon what cell is active (versus the value of said cell)? 关于如何根据哪个单元处于活动状态(相对于所述单元的值)运行逻辑的思考? Thanks! 谢谢!

G G

You want to use ActiveCell.Address It will tell you a value like $A$1, which you can then use in your comparison. 您想使用ActiveCell.Address它会告诉您一个类似于$ A $ 1的值,然后您可以在比较中使用它。

Try this sample code to see how the returned value is formatted: 尝试使用以下示例代码来查看返回值的格式:

Sub selectRange() MsgBox ActiveCell.Address End Sub

For your case, you'd want something like 对于您的情况,您想要类似

If ActiveCell.Address = "$C$36" Then

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

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