2017-06-05 26 views
0

我正在嘗試編寫代碼以循環遍歷工作簿中除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

裏面你Ÿ循環您引用ActiveSheet。這就是爲什麼你只更新一張表。 –

+1

@BrianMStafford在'x'循環中,'Sheets(x).Select'將改變表單。仍然效率低下 – Dave

+0

@Dave你是對的。我錯過了那行代碼! –

回答

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

無需爲此選擇每個工作表,或者使用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 
+0

謝謝,這很好 – jabezs09

0

問題是,您選擇工作表,但不要使用Sheet.Activate。接下來你使用ActiveSheet。這是更好地避免選擇紙張乾脆只是工作對工作表對象(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