0

我正在尝试从具有最新日期的工作簿中选择一张工作表。每张纸的日期都在相同的空间中,否则它是空白或文本,因此不应评估为大于我认为的整数或日期格式的值。一旦我找到该表,我想获取特定数据并使用它。我的问题是选择正确的工作表。这是代码:

Dim wksht As Worksheet
Dim maxsheet As Worksheet
Dim currentdate as Integer
Dim maxdate as Integer

'go through each worksheet. compare the value of current date extracted from each sheet
'to maxdate. If currentdate > maxdate maxdate = currentdate.
'remember the worksheet for maxdate as maxsheet.

maxdate = 0
For Each wksht In ActiveWorkbook.Worksheets
    With wksht
        currentdate = wksht.Range("B1").Value
        If currentdate > maxdate Then
            maxsheet = wksht
            maxdate = currentdate
        End If
    End With
Next wksht

到底是怎么回事?我得到的错误是“'91':对象变量或未设置块变量。” 我不太了解帮助部分或如何修复它。

再次查看代码,我预见到另一个问题,一旦我存储了工作表,就可以使用工作表。我可以只使用 maxsheet.select 吗?

4

4 回答 4

1

两件事情:

  1. 您正在初始化currentdate,并且maxdate作为integer; 使用date数据类型。

  2. 你有maxsheet = wksht,什么时候应该set maxsheet = wksht

至于您的其他问题,是的,您可以使用maxsheet.select, 指定一个范围(maxsheet.range("B4")例如),具体取决于您需要检索的数据。

于 2012-09-25T20:04:57.707 回答
1

循环逻辑对我来说看起来不错。你是正确的With wksht/End With没有被使用。要使用,它将是:

For Each wksht In ActiveWorkbook.Worksheets
    With wksht
        currentdate = .Range("B1").Value ` <~~~~ This guy right here
        If currentdate > maxdate Then
            maxsheet = wksht
            maxdate = currentdate
        End If
    End With
Next wksht

现在,在不了解您的工作表的情况下,我不确定我能否具体回答您的问题,但是,我会将逻辑重做如下:

[未经测试]

Dim currentdate as Date
Dim maxdate as Date
For Each wksht In ActiveWorkbook.Worksheets
    if IsDate(wksht.Range("B1").Value) then    
        currentdate = CDate(wksht.Range("B1").Value)
        If currentdate > maxdate Then
            set maxsheet = wksht
            maxdate = currentdate
        End If
    end if
Next wksht

http://p2p.wrox.com/access-vba/11341-convert-text-date-time-access.html

于 2012-09-25T20:08:27.490 回答
1

如果您将您的currentdatemaxdate变量更改为datetype 并更改maxsheetstringtype,然后将行更改为 read maxsheet = wksht.name,您将捕获页面的名称。然后您可以使用 参考该页面Worksheets(maxsheet)

于 2012-09-25T20:13:16.603 回答
0
Dim maxdate as Date
Dim wksht as Worksheet
Dim currentdate as Date
dim maxsheet as string

maxdate = 0
For Each wksht In ActiveWorkbook.Worksheets
    If IsDate(wksht.Range("B1").Value) Then
        currentdate = CDate(wksht.Range("B1").Value)
        If currentdate > maxdate Then
            maxsheet = wksht.Name

            maxdate = currentdate
        End If
    End If
Next wksht

感谢您的所有帮助。这是工作代码

于 2012-09-26T22:10:01.737 回答