0

如果日期不是今天,我有一个宏可以在日期上方插入一行数据。然后它在日期列中添加今天的日期。这是在 30 个工作表中完成的,但只有第一个工作表在正确的位置正确地添加了一行,并在正确的单元格中添加了一个日期。该行应在所有这些上插入 A3" 上方,但其余在“A4”上方插入一行。下面是我正在使用的当前代码,我认为这可能是范围问题,但在测试时没有运气。

    Sub UpdatePrices()
    Dim ws As Worksheet, Ldate As String, DateRng As Range
Set DateRng = Sheets("AXP").Range("A3")    'date range is last date
Ldate = DateRng.Value    'defines ldate as most recent date


For Each ws In ThisWorkbook.Worksheets
    ws.Select
    'Inserts a new row with containing today's Date and exclude sheets
    If Ldate <> Date And UCase(ws.Name) <> "DATA" And UCase(ws.Name) <> "UPDATE" Then
        ws.Rows(DateRng.Row).EntireRow.Insert
        ws.Cells(DateRng.Row, DateRng.Column).Offset(-1, 0) = Date
    End If

Next

End Sub
4

2 回答 2

1

当您插入一行时,您的行DateRng从 3 增加到 4。您应该将原始行号和列号存储在另一个变量中,这样它就不会改变

DateRngRow = Sheets("AXP").Range("A3").Row    'date range is last date
DateRngCol = Sheets("AXP").Range("A3").Column
Ldate = Sheets("AXP").Range("A3").Value    'defines ldate as most recent date


For Each ws In ThisWorkbook.Worksheets
    ws.Select
    'Inserts a new row with containing today's Date and exclude sheets
    If Ldate <> Date And UCase(ws.Name) <> "DATA" And UCase(ws.Name) <> "UPDATE" Then
        ws.Rows(DateRngRow).EntireRow.Insert
        ws.Cells(DateRngRow, DateRngCol) = Date
    End If

Next
于 2013-10-24T00:05:54.957 回答
0

以下代码是您的规范下的工作代码。在下面的代码中,您的原始代码也有一些非常小的速度提高:只调用一次 Date 函数,只检查最后一个日期是否小于一次日期。

您说您将始终在 3 以上插入一行,并且新行列 A 应该有日期,下面的代码将执行此操作。

Sub UpdatePrices()
Dim ws As Worksheet
Dim Ldate As Date
Dim Today As Date
Dim DateRng As Range

Set DateRng = Sheets("Sheet1").Range("A3")    'date range is last date
Ldate = CDate(DateRng.Value)    'defines ldate as most recent date
Today = Date

If Ldate < Today Then

For Each ws In ThisWorkbook.Worksheets
    ws.Select
    'Inserts a new row with containing today's Date and exclude sheets

    If UCase(ws.Name) <> "DATA" And UCase(ws.Name) <> "UPDATE" Then
        ws.Rows(3).EntireRow.Insert
        ws.Cells(3, 1) = Today
    End If

Next

End If
End Sub
于 2013-10-24T00:14:09.143 回答