2017-04-21 94 views
-1

我在工作簿中有3個工作表,1st是Info表中單元格S1有Trainer名稱,我需要在第二個表名爲類。一旦在課程表(H欄)中找到培訓師姓名,我需要將該培訓師姓名放在輸出表(下一個空行A列)中。然後,我還需要從類(A列),Grad Date(P列)中獲取類名,以及X列中的更多數據到AB。我似乎無法得到如何正確編碼,因爲我已經運行的代碼,但它不會將數據輸入到輸出表。到目前爲止,我只測試了2個字段。從另一個工作表中的單元格引用中的列中查找數據,然後將一些數據複製到另一個工作表中

Sub GetClassData() 
Dim cls As Worksheet 
Dim shOUT As Worksheet 
Set cls = Worksheets("Classes") 
Set shOUT = Worksheets("Output") 
Dim trName As Range 
Set trName = Worksheets("Info").Range("S1") 

cls.Select 
' Find the last row of data 
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 
' Loop through each row 
For x = 2 To FinalRow 
    ' Decide if to copy based on column H 
    thisvalue = Cells(x, 8).Value 
    If thisvalue = trName.Value Then 
     irow = Cells(Rows.Count, 1).End(xlUp).Row + 1 
     With shOUT 
      .Cells(irow, 1).Value = trName.Value 
      .Cells(irow, 2).Value = trName.Offset(, -7).Value 
     End With 
    End If 
Next x 
End Sub 

回答

1

嘗試下面的代碼(解釋是代碼註釋裏):

Option Explicit 

Sub GetClassData() 

Dim cls As Worksheet 
Dim shOUT As Worksheet 
Dim trName As Range 
Dim x As Long 
Dim iRow As Long 
Dim FinalRow As Long 
Dim thisvalue As String 

Set cls = Worksheets("Classes") 
Set shOUT = Worksheets("Output") 
Set trName = Worksheets("Info").Range("S1") 

With cls 
    ' Find the last row of data in Column "A" 
    FinalRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
    ' Loop through each row 
    For x = 2 To FinalRow 
     ' Decide if to copy based on column H 
     thisvalue = .Range("H" & x).Value 
     If thisvalue Like trName.Value Then ' <-- check the names 
      iRow = shOUT.Cells(shOUT.Rows.Count, "A").End(xlUp).Row + 1 

      shOUT.Range("A" & iRow).Value = thisvalue '<-- get Trainer Name 
      shOUT.Range("B" & iRow).Value = .Range("A" & x).Value '<-- get Class Name for Classes 
      ' add the rest of the thing you need to copy here 

     End If 
    Next x 
End With 

End Sub 
+0

夏嘉曦你好,感謝你的幫助。我得到一個錯誤,雖然說沒有找到FinalRow代碼的變量。 > FinalRow = .Cells(.Rows.Count,「A」)。End(xlUp).Row ... .Cells部分被突出顯示 –

+0

@CieloSalas再次嘗試,奇怪的是,我沒有複製'Dim'行(現在應該工作) –

+0

我現在得到> thisvalue = .Range(「H」&x).Value上的錯誤。我試圖設置昏暗變化,但是當我運行代碼,shout –

相關問題