VBA /宏动态范围/忽略空白

时间:2016-03-21 03:19:04

标签: vba dynamic macros range

Sub CopyRandomRows()


 Sheets("Random Sample").Select
    Cells.Select
    Range("C14").Activate
    Selection.Delete Shift:=xlUp


 Windows("Critical Infotype Raw Data.xlsx").Activate
    Rows("1:1").Select
    Selection.Copy
    Application.CutCopyMode = False
    Selection.Copy
    Windows("Critical Infotype Sampling Tool.xlsm").Activate
    Sheets("Random Sample").Select
    Rows("1:1").Select
    ActiveSheet.Paste

  Dim source As Range, target As Range, randCount&, data(), value, r&, rr&, c&

  ' this defines the source to take the data
  Set source = Workbooks("Critical Infotype Raw Data.xlsx").Worksheets("Sheet1").Range("A2:L5215")



  ' this defines the target to paste the data
  Set target = Workbooks("Critical Infotype Sampling Tool.xlsm").Worksheets("Random Sample").Range("A2")

 ' this defines the number of rows to generate based on the input in textbox
    randCount = Worksheets("Main").TextBox1.value

  ' this load the data in an array
  data = source.value

  'this shuffle the rows
  For r = 1 To randCount
    rr = 1 + Math.Round(VBA.rnd * (UBound(data) - 1))
    For c = 1 To UBound(data, 2)
      value = data(r, c)
      data(r, c) = data(rr, c)
      data(rr, c) = value
    Next
  Next

  ' this writes the data to the target
  target.Resize(randCount, UBound(data, 2)) = data

   MsgBox "Random Sample Generated!"

End Sub

以上是根据我在文本框中的输入从另一个工作簿中获取/生成随机样本数据的完整代码。

我的问题是这段代码:

'这定义了获取数据的来源

Set source = Workbooks("Critical Infotype Raw Data.xlsx").Worksheets("Sheet1").Range("A2:L5215")

我希望范围不具体,以便我可以使用任何数据并获得随机样本而不会出现问题。此外,当我只得到10个数据时,它总是给我空白,因为它甚至在范围内得到空白的行,所以我希望范围不具体。我该怎么做?提前谢谢你。

1 个答案:

答案 0 :(得分:1)

不管选择Range("A2:L5215"),无论整个范围内是否有任何数据,您都可以通过

之类的方式确定输入表的使用范围。
With Workbooks("Critical Infotype Raw Data.xlsx").Worksheets("Sheet1")
    Set Source = .Range("A1:" & .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, .Cells(1, .Columns.Count).End(xlToLeft).Column).Address)
End With

请注意,这是通过查找A列中最后一个填充的行和第1行中最右边的填充单元格来确定数据的大小。