2016-07-27 40 views
-1

多列这是一个具有不同的列如D_ID,模块,函数名等我的消息来源表进口从一张新纸

enter image description here

我想出口几列,比如“D_ID “,”Function_Name“,”Sub_Unit_Number“,”长度“从ActiveSheet到新的工作表。

我的输出工作应该是这样的:

enter image description here

,我试图用首先使用VBA代码来创建一个新的工作表,然后使用for循环来遍历范围的逻辑(” A1:K1“)来查找该范围内的每个单元格值是否与字符串”D_ID“,”Function_Name“,”Sub_Unit_Number“,”length“匹配。如果是的话,那么我需要写在新的工作表中。

但我的逻辑失败了。

我真的很感激,如果有人可以帮助我用不同的逻辑或代码来获得它的工作。

  Sub CreateNewSheet() 
     Dim rep As Integer 
     Dim sheet_name_to_create As String 

     sheet_name_to_create = "Test_Sheet" 

     'a statement to go through other worksheets 
     For rep = 1 To (Worksheets.Count) 

      'search the sheet wth the name if that exists 
     If LCase(Sheets(rep).Name) = LCase(sheet_name_to_create) Then 
      MsgBox "This sheet already exists" 
     Exit Sub 
     End If 

     Next 

      Sheets.Add After:=Sheets("Original_Sheet") 
      Sheets(ActiveSheet.Name).Name = sheet_name_to_create 

      End Sub 

      Sub Extract_data() 
      ' this sub routine extracts D_ID, Function_Name, Sub_Unit_Number     
      'and Length from the Original_Sheet 
      Dim LastColumn As Integer 
      Dim cell As Range 
      Dim sht As Worksheet 
      Dim data As String 


     Set sht = Worksheets("Original_Sheet") 
     LastColumn = sht.Cells(1, .Columns.Count).End(xlToLeft).Column 

     For Each cell In sht.Range("A1:K" & LastColumn).Cells 

     data = cell.Value 
      If data = "D_ID" Then 
      ' I need to import to the new worksheet 

      ElseIf data = "Function_Name" Then 
      ' I need to import to the new worksheet 

      ElseIf data = "Sub_Unit_Number" Then 
       ' I need to import to the new worksheet 

      ElseIf data = "Length" Then 
       ' I need to import to the new worksheet 

      End If 
      End Sub 


      Sub MyNewProcedure() 
      Call CreateNewSheet 
      Call Extract_data 
      End Sub 
+3

提交到目前为止编写的代码。 – nilsman

+0

@nilsman我已经添加了代码,但它不完全正确,因为我现在使用vba进行此任务,并且我不熟悉语法和全部。 – user28

回答

0

我不知道到底是什么问题,但我试了一下。你得到的代码完美,只有一两个错误。

LastColumn = sht.Cells(1, ->here<-.Columns.Count).End(xlToLeft).Column 

的.Columns需要一个对象,这将是sht.Columns.count

Next cell 

是最后下完缺少如果是这样的for循环得到了一个未来

然后你只需要在不同的表上写下这个名字:

Set sht = Worksheets("Orignal Sheet") 

然后你需要把一个副本在If body中引用当前列的命令,如下所示:

data = cell.Value 
     If data = "D_ID" Then 
     MsgBox ("Got it") 
     Sheets("Table3").Columns(cell.Columns).Copy Destination:=Sheets("Table4").Columns(2) 
+0

谢谢。我做了一些小的改变,它的工作.. – user28

相关问题