我想遍历工作簿中的所有页面,然后写入所有这些单元格。我想说的是,鉴于我目前在特定工作表中写入特定单元格的单元格。我怎样才能这样做,这就是细胞=" foo"那个"这个工作"写入相同的单元格代码,但是在新的工作表中。
Sub WorksheetLoop()
Dim ws As Worksheets beginning
Dim starting_ws As Worksheet
Set starting_ws = ActiveSheet
ws_num = ThisWorkbook.Worksheets.Count
For I = 1 To ws_num
ThisWorkbook.Worksheets(I).Activate
For Each Cell In Range("G9:G39").Cells
If Cell = "foo" Then
Sheets("mysheet").Cell.Value = "this worked"
Cell = "this worked"
Exit For
Next
Next
End Sub
答案 0 :(得分:0)
考虑:
Sub WorksheetLoop()
ws_num = ThisWorkbook.Worksheets.Count
For I = 1 To ws_num
ThisWorkbook.Worksheets(I).Activate
Range("G9:G39").Value = "this worked"
Next
End Sub
您无需遍历工作表中的单个单元格,也不需要Activate
:
Sub WorksheetLoop2()
ws_num = ThisWorkbook.Worksheets.Count
For I = 1 To ws_num
With ThisWorkbook.Worksheets(I)
.Range("G9:G39").Value = "this worked"
End With
Next
End Sub
答案 1 :(得分:0)
你可能在此之后:
Sub WorksheetLoop()
Dim sht As Worksheet
Dim cell As Range
For Each sht In ThisWorkbook.Worksheets ' loop through sheets
If sht.Name <> "mysheet" Then ' avoid considering "mysheet" sheet
For Each cell In sht.Range("G9:G39") ' loop through current sheet range "G9:G39"
If cell.Value = "foo" Then Sheets("mysheet").Range(cell.Address).Value = "this worked" ' if current cell value is "foo" then write "This worked" in corresponding cell of "mysheet" sheet
Next
End If
Next
End Sub
答案 2 :(得分:0)
您需要指定范围对象引用的工作表。为方便起见,每个工作范围的左上角也是。
Sub WorksheetLoop()
Dim i As Long, j As Long, ws_num As Long
ws_num = ThisWorkbook.Worksheets.Count
Dim ws As Worksheet, rng As Range
Dim my_ws As Worksheet, my_rng As Range
Set my_ws = Sheets("mysheet")
Set my_rng = my_ws.Range("G9")
For i = 1 To ws_num
Set ws = ThisWorkbook.Worksheets(i)
Set rng = ws.Range("G9")
' Go down 30 cells from G9
For j = 1 To 30
If rng.Cells(j, 1).Value = "foo" Then
my_rng.Cells(j, 1).Value = "this worked"
rng.Cells(j, 1).Value = "this worked"
End If
Next j
Next
End Sub
警告 ws
指向Sheet("mysheet")
时会发生什么?