我正在尝试编写代码来循环遍历工作簿中的所有工作表,除了1,并添加一个列,其中包含3个其他工作表。这似乎遍历一个工作表的所有行,但不是书中的其他行
Sub addConcats()
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
'Run through worksheets
Dim x As Long
Sheet1.Select
For x = 2 To ThisWorkbook.Sheets.Count
If Sheets(x).Name <> "VAT Transaction Report" Then Sheets(x).Select
Replace:=False
Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
For y = 2 To LastRow
'Concat
ActiveSheet.Cells(y, 20).Value = ActiveSheet.Cells(y, 7).Value &
ActiveSheet.Cells(y, 9).Value & ActiveSheet.Cells(y, 12).Value
Next y
Next x
End Sub
答案 0 :(得分:1)
请尝试以下代码,以便For
循环考虑您要更新的Sheets(x)
:
Dim LastRow As Long
For x = 2 To ThisWorkbook.Sheets.Count
If Sheets(x).Name <> "VAT Transaction Report" Then
With Sheets(x)
LastRow = .UsedRange.Row - 1 + .UsedRange.Rows.Count
For y = 2 To LastRow
'Concat
.Cells(y, 20).Value = .Cells(y, 7).Value & .Cells(y, 9).Value & .Cells(y, 12).Value
Next y
End With
End If
Next x
答案 1 :(得分:1)
无需为此选择每个工作表,也无需使用x和y运行。
Sub addConcats()
Dim sh As Worksheet
Dim LastRow As Long
For Each sh in ThisWorkbook.Worksheets
If sh.Name <> "VAT Transaction Report" Then
LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp)
For y = 2 To LastRow
'Concat
sh.Cells(y, 20).Value = sh.Cells(y, 7).Value & sh.Cells(y, 9).Value & sh.Cells(y, 12).Value
Next y
End If
Next
End Sub
答案 2 :(得分:0)
问题是您选择了一个工作表,但不使用Sheet.Activate。接下来使用ActiveSheet。最好避免完全选择工作表,只是对着一个Worksheet对象(sh变量)
尝试以下方法:
Sub addConcats()
Dim sh As Worksheet
Dim x As Integer
Dim y As Integer
Dim LastRow As Long
For x = 1 To ThisWorkbook.Sheets.Count
Set sh = Sheets(x)
If sh.Name <> "VAT Transaction Report" Then
LastRow = sh.UsedRange.Rows.Count
For y = 2 To LastRow
'Concat
sh.Cells(y, 20).Value = sh.Cells(y, 7).Value & sh.Cells(y, 9).Value & sh.Cells(y, 12).Value
Next y
End If
Next x
End Sub