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 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

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

4

1 回答 1

2

在这一行:

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

您正在为 Range 的第一次调用指定“测试”工作簿,但不是为第二次调用指定,也不是为 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
于 2013-10-17T12:38:40.080 回答