我正在尝试创建一个按钮,该按钮将根据函数读取的日期来隐藏行。
我的excel工作表用于会议记录,基于D列,我将决定是隐藏还是显示单元格行。现在,D列包含特定分钟的日期,但偶尔包含一个名为“ Date”的字符串作为标题行的一部分。由于某些原因,我无法成功编写if语句来跳过所述行。因此,在为变量Current_Date分配默认VBA日期值并且代码崩溃时,我遇到了错误。
我确保在电子表格中将这些特定单元格的格式设置为“文本”,但是看来我的if语句仍然无法执行。
有人可以给我一些指导吗?
谢谢。
Private Sub CommandButton1_Click()
Dim x As Integer
Dim Current_Date As Date
Dim Last_Meeting_Date As Date
Dim default_date As Date
' Loop to hide old meeting minutes
For x = 150 To 1000
If Worksheets("Minutes").Cells(x,4) = "Date" Then
x = x + 1
End If
Current_Date = Worksheets("MINUTES").Cells(x, 4)
Last_Meeting_Date = Worksheets("HOME").Cells(19, 16)
If Current_Date < Last_Meeting_Date Then
Worksheets("MINUTES").Rows(x).Hidden = True
End If
Next x
End Sub
答案 0 :(得分:2)
您可以尝试:
Private Sub CommandButton1_Click()
Dim x As Integer
Dim Current_Date As Date
Dim Last_Meeting_Date As Date
Dim default_date As Date
Last_Meeting_Date = Worksheets("HOME").Cells(19, 16)
' Loop to hide old meeting minutes
For x = 150 To 1000
If Worksheets("Minutes").Cells(x,4) <> "Date" Then 'You might want to use IsDate()?
Current_Date = Worksheets("MINUTES").Cells(x, 4)
'original code is only able to hide row, this one can unhide them as well
Worksheets("MINUTES").Rows(x).Hidden = (Current_Date < Last_Meeting_Date)
End If
Next x
End Sub
答案 1 :(得分:1)
在重新格式化和简化您的代码方面,我获得了一些自由。我对声明进行了重新排序,删除了“默认日期”,因为它没有被使用,将对“ 4”列的引用更改为“ D”,颠倒了if语句的逻辑,并使用了“ With”语句来防止重复指定工作表
Private Sub CommandButton1_Click()
Dim Last_Meeting_Date As Date
Last_Meeting_Date = CDate(Worksheets("HOME").Cells(19, 16).Value2)
Dim x As Long
Dim Current_Date As Date
' Loop to hide old meeting minutes
With Worksheets("MINUTES")
For x = 150 To 1000
If CStr(.Cells(x, "D").Value2) <> "Date" Then
Current_Date = CDate(.Cells(x, "D").Value2)
If Current_Date < Last_Meeting_Date Then .Rows(x).Hidden = True
End If
Next x
End With
End Sub