2016-07-22 66 views
0

我是使用visual basic的初學者,但遇到了一些小問題。我想要做的是採用Excel電子表格並搜索特定列以查找名稱,然後抓取該行中的所有內容以便將其轉移到另一個表單中。除了因爲我不明白的原因而陷入無限循環之外,我已經運行了所有程序。在Visual Basic中搜索已填充的單元格

'set up a for loop that increments through all sheets in the workbook 
For i = 1 To ThisWorkbook.Sheets.Count 
'set up a temp page to work with the current page 
    Set tem = ThisWorkbook.Sheets(i) 
    'increment through all the rows that have data in them 
     For Each rng In tem.Rows 
     'if the data matches what was searched for, copy it into another worksheet 
      If tem.Cells(ct, 4) = SForm.Text Then 
       sr.Cells(spot, 1) = tem.Cells(ct, 1) 
       sr.Cells(spot, 2) = tem.Cells(ct, 2) 
       sr.Cells(spot, 3) = tem.Cells(ct, 3) 
       sr.Cells(spot, 4) = tem.Cells(ct, 4) 
       sr.Cells(spot, 5) = tem.Cells(ct, 5) 
       sr.Cells(spot, 6) = tem.Cells(ct, 6) 
       sr.Cells(spot, 7) = tem.Cells(ct, 7) 
       sr.Cells(spot, 8) = tem.Cells(ct, 8) 
       sr.Cells(spot, 9) = tem.Cells(ct, 9) 
       sr.Cells(spot, 10) = tem.Cells(ct, 10) 
       sr.Cells(spot, 11) = tem.Cells(ct, 11) 
       sr.Cells(spot, 12) = tem.Cells(ct, 12) 

       'increment the placeholder for the new sheet 
       spot = spot + 1 
      End If 
      'increase ct to keep track of where in the worksheet it is 
      ct = ct + 1 
     Next rng 
     'reset ct for the next worksheet 
     ct = 1 
Next i 

我遇到的具體問題是溢出,因爲ct是int和maxes。這告訴我我手上有一個無盡的循環。

感謝您的幫助提前。

+0

您正在迭代每張紙100萬次以上,這將需要一段時間。另外你不需要'ct'。取而代之的是使用'rng.row'。 –

+0

在[此鏈接](http://www.globaliconnect.com/excel/index.php?option=com_content&view=article&id=112:find-method-in-excel-vba-find-multiple-occurrences-find-method -lookup-find-date&catid = 79&Itemid = 475)查看**示例 - 在一個範圍內查找多個值。**。它會在這裏爲你服務。另外,你沒有一個無限循環。該代碼被寫入檢查**工作表中的每行**,而不管那裏是否有數據。所以一旦該行變得大於〜38,562(沒有確切的手數),那麼'Integer'變量就不能再保存它了。 –

回答

0

您正在迭代每張紙100萬次以上,這將需要一段時間。找到列D中的最後一個單元格,並只遍歷這些行

另外,您不需要ct。取而代之的是使用rng.row。

然後將整個值賦值合併成一行。

For i = 1 To ThisWorkbook.Sheets.Count 
'set up a temp page to work with the current page 
Set tem = ThisWorkbook.Sheets(i) 
'increment through all the rows that have data in them 

    For Each rng In tem.Range("D1", tem.Cells(tem.Rows.Count, 4).End(xlUp)) 
    'if the data matches what was searched for, copy it into another worksheet 
     If rng.Value = SForm.Text Then 
      sr.Range(sr.Cells(spot, 1), sr.Cells(spot, 12)).Value = tem.Range(tem.Cells(rng.Row, 1), tem.Cells(rng.Row, 12)).Value 
      'increment the placeholder for the new sheet 
      spot = spot + 1 
     End If 
    Next rng 
Next i 

爲了使它更快考慮丟棄的整個範圍到一個數組並輸出到另一個陣列來最小化片和VBA之間的相互作用。

+0

我使用你的建議再次運行程序,似乎它有一個複製數據的問題。如果其中一個區域中的某個單元格爲空白,您使用的方法是否存在問題?如果是這樣,是否有解決這個問題的方法?我得到一個「對象的方法範圍」_worksheet「失敗」的錯誤。我認爲這意味着它發現了一些它不能複製的東西,或者它不能複製到特定的位置。 – Rejera

+0

@Rejera不好意思,我的錯誤。我忘記將Cells()限定在適當的出身位置。請參閱編輯,您可能需要刷新屏幕。 –

+0

對,對。我應該看到這一點。現在就像魅力一樣。謝謝。 – Rejera

相關問題