从另一个工作表中选择一个随机单元格

时间:2013-10-17 12:27:27

标签: excel excel-vba vba

我正在尝试从另一个工作表中选择一个随机单元格。如果我在代码所在的当前工作表上选择一个随机单元格,则以下代码有效。如何从其他工作表中选择随机单元格?

Dim e
Static myList As Object
If myList Is Nothing Then
    Set myList = CreateObject("System.Collections.SortedList")
End If
If myList.Count = 0 Then
    Randomize
    For Each e In Range("D3:D32", Range("D" & Rows.Count).End(xlUp)).Value
        myList.Item(Rnd) = e
    Next
End If
MsgBox myList.GetByIndex(0)
myList.RemoveAt 0

这是我试图从另一张纸上选择的内容。

Dim e
Static myList As Object
If myList Is Nothing Then
    Set myList = CreateObject("System.Collections.SortedList")
End If
If myList.Count = 0 Then
    Randomize
    For Each e In Workbooks("Test").Sheets("Sheet1").Range("D3:D32", Range("D" & Rows.Count).End(xlUp)).Value
        myList.Item(Rnd) = e
    Next
End If
MsgBox myList.GetByIndex(0)
myList.RemoveAt 0

关于我做错了什么的建议?

1 个答案:

答案 0 :(得分:2)

在这一行:

For Each e In Workbooks("Test").Sheets("Sheet1").Range("D3:D32", Range("D" & Rows.Count).End(xlUp)).Value

您指定第一次调用Range的“Test”工作簿,但不是第二次调用,也不是Rows.Count(尽管这可能是相同的)。快速修复:

For Each e In Workbooks("Book2").Sheets("Sheet1").Range("D3:D32", Workbooks("Book2").Sheets("sheet1").Range("D" & Workbooks("Book2").Sheets("sheet1").Rows.Count).End(xlUp)).Value

或:

With Workbooks("Book2").Sheets("Sheet1")
    For Each e In .Range("D3:D32", .Range("D" & .Sheets("sheet1").Rows.Count).End(xlUp)).Value