2012-10-19 87 views
0

我正在编写我的第一个宏,并对如何根据特定列中的值选择特定行存在疑问。这里是我到目前为止的代码:Excel宏:根据列日期选择特定行

Sub Pipeline() 

'Module 3 
'Iterating through the Funding Date Column and looking for clients going live within 30 days 
'Selecting the rows for each client in that target range 
'TODO: Export information into an email template in Outlook 
'TODO: Send email to distribution list 


Dim fundingDate As range 
Set fundingDate = range("M4:M500") 

Dim todaysDate As Date 
todaysDate = Date 

For Each cell In fundingDate 
    If cell < todaysDate + 30 Then 
    'Need to select the entire row 
    Else 
    cell.Font.ColorIndex = 3 
End If 
Next 

End Sub 
+0

既然你说这是你的第一个宏,这里有一个提示:总是使用'​​Option Explicit'(把它作为你模块的第一行)。这将迫使你声明你的变量。 –

回答

3

cell.entirerow.select

UPDATE 这是一种更有效的方式来获得你所需要的,不用所有循环替换'Need to select the entire row

在你的代码替换For Each cell ...Next与此:

With fundingDate  
    .AutoFilter 1, "<" & todaysDate + 30   
    .SpecialCells(xlCellTypeVisible).Select 
    'here are your clients going live in next 30 days  
    .AutoFilterMode = False  
End With 

您可能需要提供一些错误的情况下,你没有客户在30天内上线(SpecialCells方法将在此检查失败)以及如果M4不是您的列标题,您可能需要调整范围如何拾取可见单元格。

+0

嗨斯科特,.AutoFilter如何工作?我认为点符号必须用于调用对象上的方法吗?另外,当我复制并粘贴上面的代码时,我收到一个错误,因为.AutoFilterMode = False,上面写着“运行时错误438,对象不支持这种方法或方法” – BC00

+0

另外,我将如何指定我希望工作表只显示一行(对于分组的行)?谢谢! – BC00

+0

@ BC00 - >现在我已经跑出了门,但为了帮助您解决问题:'.AutoFilter如何工作? - 请参阅Excel中的帮助。或者在任何给定的范围上手动使用Filter方法来查看它是如何工作的。 '。 notation' - >这在一个对象上调用一个方法。您正在调用'fundingDate'范围对象的'AutoFilter'方法,它只是使用'With'语句来使代码更易于阅读并且更高效。 'RunTime Error' - >确保你有一个可以按日期过滤的有效范围。在那里玩得开心! –