VBA Excel 循环浏览工作表,找到表格中的最后一行并自动填充数据

问题描述 投票:0回答:2

我需要一个脚本来循环遍历工作簿中的所有工作表,并在每个工作表(第一张工作表除外)的表格末尾添加 2(或更多)列。 在这种情况下,我需要添加“是”和“否”列。

添加的列 YES 和 NO 需要自动填充到末尾,如下面的示例所示。


Sub LoopSheetsAddDataFilledColumns()

Dim LastRow As Long
Dim LastCol As Long
Dim iRow As Long
Dim ws As Worksheet

For Each ws In Worksheets

Set ws = Sheets(2)

With ws
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    .Columns(LastCol + 1).EntireColumn.Insert
    .Cells(1, LastCol + 1).Value = "YES"
    .Columns(LastCol + 2).EntireColumn.Insert
    .Cells(1, LastCol + 2).Value = "NO"

End With

Next

End Sub

问题在于:

  • 此脚本仅在第一张纸上添加几列“是”和“否”,
  • 它不会一直填充到最后,
  • 特定纸张也不例外,

有人可以帮忙更新这个脚本吗?预先感谢您。

excel vba foreach autofill
2个回答
1
投票

尝试修改您的代码

Sub LoopSheetsAddDataFilledColumns()

Dim LastRow As Long
Dim LastCol As Long
Dim iRow As Long
Dim ws As Worksheet

For Each ws In Worksheets

If ws.Name <> Sheets(1).Name Then
With ws
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    .Columns(LastCol + 1).EntireColumn.Insert
    .Columns(LastCol + 2).EntireColumn.Insert
        
    .Range(.Cells(1, LastCol + 1), .Cells(LastRow, LastCol + 1)).Value = "YES"
    .Range(.Cells(1, LastCol + 2), .Cells(LastRow, LastCol + 2)).Value = "NO"

End With
End If
Next

End Sub


0
投票

试试这个:

Sub LoopSheetsAddDataFilledColumns()

Dim ws As Worksheet, rg As Range
Dim i As Long

For i = 2 To ThisWorkbook.Worksheets.Count
    Set rg = ThisWorkbook.Worksheets(i).UsedRange
    With rg
        .Offset(, .Columns.Count).Resize(, 1).Value = "YES"
        .Offset(, .Columns.Count + 1).Resize(, 1).Value = "NO"
    End With
Next

End Sub

它会循环第二张开始的所有工作表。

它使用

UsedRange
Offset
Resize
旁边写入新列。假设当前数据处于连续范围内。

© www.soinside.com 2019 - 2024. All rights reserved.