这是我的源表,它有不同的列,如D_ID,Modules,Function_Name等。
我想导出一些列,例如" D_ID"," Function_Name"," Sub_Unit_Number"," length"从ActiveSheet到新工作表。
我的输出工作表应如下所示:
我尝试使用的逻辑是首先使用vba代码创建一个新工作表,然后使用for循环遍历Range(" 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
答案 0 :(得分:0)
我不确切地知道问题是什么,但我试试看。你得到的代码完美无缺,只有一两个错误。
LastColumn = sht.Cells(1, ->here<-.Columns.Count).End(xlToLeft).Column
.Columns需要一个对象,这里它是sht.Columns.count
Next cell
在最后一个结束时丢失如果是这样,for循环得到了下一个
然后你只需要在这一点上写出不同表格的名称:
Set sht = Worksheets("Orignal Sheet")
然后你需要在if体中放一个复制命令来引用当前列,如下所示:
data = cell.Value
If data = "D_ID" Then
MsgBox ("Got it")
Sheets("Table3").Columns(cell.Columns).Copy Destination:=Sheets("Table4").Columns(2)