2015-10-09 25 views
0

有關爲什麼下面的代碼不會循環通過工作表的任何想法?對於工作簿中的每個工作表

我想根據表名稱是什麼設置每個工作表中的一列。它陷在活動工作表中,並忽略了If ws.Name <> "Default"。這被構建爲模塊:

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 

回答

4

許多所使用的對象的refences不合格並因此指活性片。在每個對象的開始處添加ws.對象限定。

3

您可能想明確聲明您的rng範圍的工作表。 (我假設它將在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 

編輯:我也敢肯定你不要用for循環所需要的with rng因爲你遍歷它,並在With聲明不一定使用rng.____

1

這是因爲您在訪問範圍時沒有引用ws變量。

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

注意:當你不添加的範圍和電池片的資格,他們是從ActiveSheet拍攝。這就是爲什麼你的代碼被卡在ActiveSheet上。

0

到目前爲止的答案已經被發現:問題是缺少for塊rng的資格。 ,雖然說,一個快速另外一條線將解決這一問題:

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

激活工作表將使代碼的其餘部分去很好的,因爲你是在/在思考活動工作表,並你只是讓那一個點亮。

0

我認爲你的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 
相關問題