对于工作簿中的每个工作表

有关为什么下面的代码不会循环通过工作表的任何想法?

我试图根据表格名称在每个表格中设置一个列。 它陷在活动工作表中,并忽略If ws.Name <> "Default" 。 这是作为一个模块构build的:

 Sub LangID_update() Dim wb As Workbook: Set wb = ThisWorkbook Dim ws As Worksheet Dim LastCol As Integer Dim LastRow As Integer Dim rng As Range Application.ScreenUpdating = False For Each ws In wb.Worksheets If ws.Name <> "Default" Then LastCol = ws.Cells(1, Columns.count).End(xlToLeft).Column LastRow = ws.Cells(Rows.count, 1).End(xlUp).Row Set rng = Range(Cells(2, LastCol + 1), Cells(LastRow, LastCol + 1)) With rng For Each c In Range(Cells(2, LastCol + 1), Cells(LastRow, LastCol + 1)) If ws.Name = "ARGS" Then c.Value = "ESP" If ws.Name = "AUTS" Then c.Value = "GR" If ws.Name = "DEUS" Then c.Value = "GR" Next c End With End If Next Application.ScreenUpdating = True Set wb = Nothing Set ws = Nothing Set rng = Nothing End Sub 

你使用的许多对象的refences是不合格的,因此参考活动工作表。 添加ws. 每个对象开始时的对象限定。

你可能会想显式声明你的范围的工作表。 (我假设它将在ws )。

尝试这个:

 Sub LangID_update() Dim wb As Workbook: Set wb = ThisWorkbook Dim ws As Worksheet Dim LastCol As Integer Dim LastRow As Integer Dim rng As Range Application.ScreenUpdating = False For Each ws In wb.Worksheets If ws.Name <> "Default" Then LastCol = ws.Cells(1, Columns.count).End(xlToLeft).Column LastRow = ws.Cells(Rows.count, 1).End(xlUp).Row Set rng = ws.Range(ws.Cells(2, LastCol + 1), ws.Cells(LastRow, LastCol + 1)) With rng For Each c In rng If ws.Name = "ARGS" Then c.Value = "ESP" If ws.Name = "AUTS" Then c.Value = "GR" If ws.Name = "DEUS" Then c.Value = "GR" Next c End With End If Next ws Application.ScreenUpdating = True Set wb = Nothing Set ws = Nothing Set rng = Nothing End Sub 

编辑:我也很确定,你不需要with rng因为你循环通过for循环,并不一定使用rng.____With语句。

那是因为你在访问范围时没有引用wsvariables。

 Set rng = Range(ws.Cells(2, LastCol + 1), ws.Cells(LastRow, LastCol + 1)) For Each c In rng 

注意:当您不为范围和单元格添加图纸限定时,它们将从ActiveSheet中获取。 这就是为什么你的代码卡在ActiveSheet上。

到目前为止的答案已经出现:问题在于缺less对于区块的rng资格。 尽pipe如此,快速添加一行将解决这个问题:

If ws.Name <> "Default" Then ws.Activate

激活工作表将使其余的代码正常工作,因为您正在/正在考虑活动工作表,而您只是让这个工作表点亮。

我认为你的For Each系列有问题,但是没有看到后面的内容,这很难说。

 For Each ws In wb.Worksheets If ws.Name <> "Default" Then LastCol = ws.Cells(1, Columns.count).End(xlToLeft).Column LastRow = ws.Cells(Rows.count, 1).End(xlUp).Row 'next line is useless 'Set rng = Range(Cells(2, LastCol + 1), Cells(LastRow, LastCol + 1)) With rng ' qualify Range and Cells For Each c In ws.Range(ws.Cells(2, LastCol + 1), ws.Cells(LastRow, LastCol + 1)) If ws.Name = "ARGS" Then c.Value = "ESP" If ws.Name = "AUTS" Then c.Value = "GR" If ws.Name = "DEUS" Then c.Value = "GR" Next c End With End If Next