VBA Excel此循环的一半有效

时间:2018-08-06 14:56:29

标签: excel vba excel-vba

因此,当我运行此宏时,正如我希望的那样,A列将用P填充,C列将用7填充。

但是,我还需要H和I列分别填充01

但是,在工作簿上,每个工作表都将填充H和I列。将仅填充H2和I2。在某些工作表中,H2和I2分别是日期(1/0/1900),(1/1/1900)。在其他工作表中,H2和I2分别只有0和1。

为什么会这样?为什么有些不正确的列日期是数字,而另一些是数字?如何解决?

Dim i As Long
Dim LastRow As Long

For i = 1 To Worksheets.count
    With Sheets(i)
      LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
      .Range("A2:A" & LastRow).Value2 = "P"
      LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
      .Range("C2:C" & LastRow).Value2 = "7"
      LastRow = .Cells(Rows.Count, "H").End(xlUp).Row
      .Range("H2:H" & LastRow).Value2 = "0"
      LastRow = .Cells(Rows.Count, "I").End(xlUp).Row
      .Range("I2:I" & LastRow).Value2 = "1"
    End With
Next i

1 个答案:

答案 0 :(得分:0)

我猜您已经运行了两次代码,并且看不到代码有任何变化。要查看它在每次运行时添加更多的值,请执行以下操作:

Sub Test()
    Dim i As Long
    Dim LastRow As Long

    For i = 1 To Worksheets.Count
        With Sheets(i)
            .Columns("A:XFD").NumberFormat = "General"
            LastRow = .Cells(Rows.Count, "A").End(xlUp).Row + 1
            .Range("A2:A" & LastRow).Value2 = "P"
            LastRow = .Cells(Rows.Count, "C").End(xlUp).Row + 1
            .Range("C2:C" & LastRow).Value2 = "7"
            LastRow = .Cells(Rows.Count, "H").End(xlUp).Row + 1
            .Range("H2:H" & LastRow).Value2 = "0"
            LastRow = .Cells(Rows.Count, "I").End(xlUp).Row + 1
            .Range("I2:I" & LastRow).Value2 = "1"
        End With
    Next i    
End Sub

(1/0/1900)(1/1/1900)的问题在于这些单元格的格式设置为日期。 0被翻译为1/0/1900,而11/1/1900。为了解决这个问题,在上面的代码中,使用以下行将单元格的格式设置为General

.Columns("A:XFD").NumberFormat = "General"