Excel vba宏,用于插入仅在第一个工作表上正常运行的行

时间:2013-10-23 23:16:38

标签: excel vba excel-vba

如果该日期不是今天,我有一个宏可以在日期上方插入数据行。然后它在日期列中添加今天的日期。这是在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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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