2013-04-10 65 views
0

我有以下問題:我有5000行和50列的excel表。我需要複製和粘貼表單並將第一個表中的行中的特定單元格的值導出到此表單中,但如果B1和B2中的值相同,則不要創建另一個表單,而要將其複製到第一行中的同一表單上。我添加了條件「07」,因爲我不希望excel在一個過程中創建5000張。到目前爲止我有這個:excel創建新工作表如果爲true

Sub Button1_Click() 
Dim newsheetname As String 
Dim isometry As String 
Application.ScreenUpdating = False 
Worksheets("Sheet1").Activate 
x = 2 

Do While Cells(x, 4) <> "" 

If Cells(x, 1) = "07" Then 
Sheets(Sheets.Count).Select 
Cells(33, 2) = Sheet1.Cells(x, 4)  
Cells(33, 28) = Sheet1.Cells(x, 32) 
End If 

If Cells(x, 4) <> Cells(x + 1, 4) Then 
Sheets("template").Copy After:=Sheets(Sheets.Count) 
ActiveSheet.Name = isometry 
End If 

isometry = Sheet1.Cells(x + 1, 4) 
x = x + 1 
Worksheets("Sheet1").Activate 

Loop 

End Sub 

我知道我的「代碼」很簡單,並不完美,我從VBA開始。可以有人建議如何完成它,我想這幾乎完成,但我缺少「新」表 字符串,現在我得到錯誤說,我不能有2張相同的名稱,當然。 感謝

+1

不是你問什麼,但你會更快地找到的東西,如果你避免'工作表(「工作表Sheet1」)。Activate'和'ActiveSheet'引用。儘可能使用對象和名稱。 – 2013-04-10 22:32:31

+0

在第一次迭代期間,如果條件滿足,您將嘗試將表單名稱更改爲無。在開始循環之前,移動'isometry = sheet1.cells(x + 1,4)'或設置一些名稱。你還需要什麼?你有什麼錯誤?要在最後添加一個新工作表,在我的第一個工作表上使用這個簡單的線條'Sheets.Add After:= Sheets(Sheets.Count)' – 2013-04-10 22:38:17

+0

,(x,1)和(x + 1,1)中的值是相同的並且代碼正嘗試用現有工作表的名稱創建新工作表。我想要的是,如果x = x + 1或x = x-1,則將該行中的單元格添加到現有工作表,並且不要創建新工作單元... – 2013-04-10 22:43:51

回答

0
Sub Button1_Click() 
    Dim newsheetname As String 
    Dim isometry As String 
    Dim newSheet As Worksheet 
    Application.ScreenUpdating = False 
    x = 2 

    'Go down the Sheet1 until we find a blank cell in column 4 
    Do While Worksheets("Sheet1").Cells(x, 4) <> "" 

     'If we find the value 07, copy two values to the isometry sheet 
     If Sheet1.Cells(x, 1) = "07" Then 

      isometry = Sheet1.Cells(x, 4) 

      'create the sheet if it does not exist 
      If Not SheetExists(isometry) Then 
       Sheets("template").Copy After:=Sheets(Sheets.Count) 
       Sheets(Sheets.Count).Name = isometry 
      End If 

      'Copy our data 
      Sheets(isometry).Cells(33, 2) = Sheet1.Cells(x, 4) 
      Sheets(isometry).Cells(33, 28) = Sheet1.Cells(x, 32) 
     End If 

     'Move on to the next row 
     x = x + 1 

    Loop 
    Application.ScreenUpdating = True 
End Sub 

Function SheetExists(isometry) As Boolean 
    Dim exists As Boolean 
    exists = False 
    For Each Sheet In Worksheets 
     If Sheet.Name = isometry Then 
      exists = True 
      Exit For 
     End If 
    Next 
    SheetExists = exists 
End Function 
+0

好吧,它將第二個工作表更名爲「isometry」我在行 表(「模板」)上得到VBA運行時錯誤9「下標超出範圍」。複製之後:=表(Sheets.Count) – 2013-04-10 22:54:01

+0

我從這裏得到了一些幫助:http:// stackoverflow。 com/questions/6040164/excel-vba-if-worksheetwsname-exists – 2013-04-10 22:58:56

+0

您有名爲「template」的工作表嗎? – 2013-04-10 22:59:58