2016-12-06 47 views
0

如果工作表名稱爲「Central」(在單詞末尾有一個空格),zone =「Central」將返回一個錯誤,並且工作表無法激活。如何設置字符串以查找工作表

我該如何糾正?

dim wb1, wb2, wb3 as workbook 
    set wb1 = activeworkbook 'the macro file 
dim ws1, ws2 as worksheet 
set ws1 = Sheets("Central Zone") 
set ws2 = Sheets("Eastern Zone") 

For x = 1 To 2 
    If x = 1 Then 
     Set ws = ws1 
     zone = "Central" 
    End If 
    If x = 2 Then 
     Set ws = ws2 
     zone = "East" 
    End If 


    wb2.Sheets(zone).Activate 'wb2 is source file 1. I have wb3, wb4, etc 
     Selection.EntireColumn.Hidden = False 
     Range("A1").Select 
     Selection.End(xlDown).Select 
     Range(Selection, Selection.End(xlUp)).Select 
     Selection.EntireRow.Select 
     Selection.Copy 
    wb1.Activate 
    ws.Activate 
     ActiveSheet.Paste 
     Application.CutCopyMode = False 
     Range("A1").Select 
     Selection.End(xlDown).Offset(1, 0).Select 
Next x 
+0

你有規定的區域內與'昏暗的區域作爲字符串字符串' –

+0

是的,我有。但問題是實際的表名不是「Central」而是「Central」。 –

+0

@AizatKassim而不是我們猜測你是如何定義'ws'的,在哪裏和什麼是'ws1',請在這裏發佈你的代碼的其餘部分。 –

回答

0

它的百達建議從ActivateSelectionSelect和所有其他 「親戚」 望而卻步。而應使用引用的對象,如Sheets和`範圍。

下面的代碼是一個有點「快速和骯髒」,但它應該給你結果你想

代碼

Option Explicit 

Sub CopyCentralSheets() 

Dim wb1 As Workbook, wb2 As Workbook, wb3 As Workbook 
Dim ws1 As Worksheet, ws2 As Worksheet, Sht As Worksheet, ws As Worksheet 
Dim LastRow As Long, LastColumn As Long, PasteRow As Long, x As Long 

Set wb1 = ThisWorkbook ' this macro file 
'Set wb2 = Workbooks("temp.xlsx") 'for my debug tests only 

Set ws1 = wb1.Sheets("Central Zone") 
Set ws2 = wb1.Sheets("Eastern Zone") 

For x = 1 To 2 
    If x = 1 Then 
     For Each Sht In wb2.Worksheets 
      If Sht.Name Like "Central*" Then 
       Set ws = Sht 
      End If 
     Next Sht 
    Else 
     If x = 2 Then 
      For Each Sht In wb2.Worksheets 
       If Sht.Name = "East" Then 
        Set ws = Sht 
       End If 
      Next Sht 
     End If 
    End If 

    With ws 
     LastRow = .UsedRange.Rows(.UsedRange.Rows.Count).Row 
     LastColumn = .UsedRange.Columns(.UsedRange.Columns.Count).Column 
     .Range(.Cells(1, 1), .Cells(LastRow, LastColumn)).Copy     
    End With 

    If x = 1 Then 
     With ws1 
      PasteRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
      .Range("A" & PasteRow + 1).PasteSpecial xlValues 
     End With 
    Else 
     If x = 2 Then 
      With ws2 
       PasteRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
       .Range("A" & PasteRow + 1).PasteSpecial xlValues 
      End With 
     End If 
    End If 
Next x 

End Sub 
+0

謝謝。讓我試試這個,我會讓你知道結果。 –

+0

我不得不做一些更改,使其與我的其他代碼一起工作。它工作得很好。非常感謝你的代碼! –

+0

@AizatKassim請將我的答案標記爲「答案」(在旁邊放一點** V **) –