在VBA中填充来自不同表格的单元格

我正在创build一个工具,用于填充第二个工作表上的零件清单(PARTS)中要审核的零件清单。 部件在类(A,B或C)中,所以工具使用随机数生成器来select要检查部件类的行。当我尝试检查部件类时会得到1004 runtime error ,帮助解决这个问题。 这里是给我一个错误的循环:

 'While loop to obtain 6 A-Class part numbers to audit Dim rand As Variant Do While Acount <= 6 'Random number generator rand = Int((6451 - 2 + 1) * Rnd + 2) 'checking part class ***If statement gives error*** If Sheets("PARTS").Cells(rand, 5).Value = "A" Then Acount = Acount + 1 'audit list copies cell from parts list Sheets("AUDIT POPULATOR").Cells(Acount, 1).Value = Sheets("PARTS").Cells(rand, 1).Value Else Acount = Acount Sheets("AUDIT POPULATOR").Cells(Acount, 1).Value = "" End If Loop 

因为你没有初始化'acount'variables,所以它是空的,因此你得到错误1004.我也build议使用'选项显式'声明来防止这样的错误。 这里是你的代码与缺less的部分:

  Option Explicit Private Sub CommandButton1_Click() 'While loop to obtain 6 A-Class part numbers to audit Dim rand As Variant Dim Acount As Integer Acount = 1 ' 1 or whatever number you would like to get start... Do While Acount <= 6 'Random number generator rand = Int((6451 - 2 + 1) * Rnd + 2) 'checking part class ***If statement gives error*** If Sheets("PARTS").Cells(rand, 5).Value = "A" Then Acount = Acount + 1 'audit list copies cell from parts list Sheets("AUDIT POPULATOR").Cells(Acount, 1).Value = Sheets("PARTS").Cells(rand, 1).Value Else Acount = Acount Sheets("AUDIT POPULATOR").Cells(Acount, 1).Value = "" End If Loop End Sub