2017-04-25 2924 views
-1

在我正在處理的工作中,我有一個關鍵的保存工作表。我創建了一個按鈕宏來嘗試執行下面的操作。VBA Excel:當數據滿足條件時,將數據從一個單元格複製到另一個單元格

我希望能夠循環訪問一列信息,並且如果某個單元格包含該列中的數據,則從同一行上的另一列中獲取數據,然後將其放入表格中其他位置的新單元格中,將其添加到最後的數據片段下面。

我的代碼如下:

Sub getLostKeys() 

    Dim k As Integer 
    Dim kMove As Integer 
    Dim cellKeyNum As String 
    Dim newCellKeyNum As String 
    Dim Kcolumn As String 
    Dim Ccolumn As String 
    Dim refCell As String 
    Dim outputCell As String 

    Kcolumn = "K" 
    Ccolumn = "C" 

    For k = 2 To 301 
     If Cells(k, 8) <> "" Then 
      cellKeyNum = CStr(k) 
      kMove = k + 6 
      newCellKeyNum = CStr(kMove) 
      refCell = Ccolumn & cellKeyNum 
      outputCell = Kcolumn & newCellKeyNum 
      Range(outputCell).Value = Range(refCell) 
     End If 
    Next k 

End Sub 

它編譯罰款和代碼運行並滿足條件不錯,但它不會移動蜂窩信息向新的小區。

任何幫助將非常感謝!

+0

您使用的變量太多。任何原因? – Masoud

+1

你的數據是什麼樣的?我不認爲*你需要一個宏,你想做什麼?如果一個單元格不是空白的,你只是想將該值放在另一列中? – BruceWayne

回答

0

而不是使用Strings設置Cell()值,你應該使用Ranges

試試這個:

Sub getLostKeys() 

Dim k  As Integer, kMove as Integer 
Dim Kcolumn As Long, Ccolumn As Long 
Dim refCell As Range, outputCell As Range 

Kcolumn = 11     ' "K" 
Ccolumn = 3     ' "C" 

For k = 2 To 301 
    If Cells(k, 8) <> "" Then 
     kMove = k + 6 
     Set refCell = Cells(k, Ccolumn) 
     Set outputCell = Cells(kMove, Kcolumn) 
     outputCell.Value = refCell.Value 
    End If 
Next k 

End Sub 

注:我做了一個假設或兩個,所以如果這樣的錯誤,或者不相當的工作,它可能有助於查看數據的樣本。

編輯另外,除非301從不會更改爲最後一行,否則如果找到第8列的lastRow,則會具有更健壯的宏,因此如果有200行或4999行,則會更具動態性併發生更改。

0
If Cells(k, 8) <> "" Then 
      kMove = k + 6 
      Range("K" & kMove).Value = Range("C" & k).Value 
End If 

應該工作(刪除所有這些無用的變量)

+0

我設法解決了這個問題,而且你是對的。有許多無用的變量。仍然習慣於VBA中的一些語法/規則。歡呼的幫助 –

相關問題