Excel 2010 VBA - 行動巨集的起點?

Excel 2010 VBA - 行動巨集的起點?

大家好(第一篇文章請耐心等待,哈哈),我已經編寫了一個宏,它完全符合我需要它做的事情,除了我無法弄清楚如何讓宏在 Sheet1 的不同單元格中啟動。目前它正在單元格 B3 中發布我需要的信息,但我希望它從單元格 B10 開始。想法?

Sub Button1_Click()

    Sheets("Sheet1").Range("B2:B600").ClearContents

    For i = 1 To 30
generate:

        RowNum = Application.RoundUp(Rnd() * 88, 0)

        If Application.CountIf(Sheets("Sheet1").[B:B], _
        Sheets("Sheet2").Cells(RowNum, "A")) = 0 Then

            Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Offset(2).Value = _
            Sheets("Sheet2").Cells(RowNum, "A").Value
        Else
            GoTo generate
        End If
    Next i

End Sub

答案1

用這個


Option Explicit

Public Sub Button1_Click()
    Const RNG = "B2:B600"   '<--- Range on Sheet1 --------------------
    Const OFFSET_ROW = 2
    Const START_ROW = 10    '<--- Start row --------------------------

    Dim ws1 As Worksheet:   Set ws1 = ThisWorkbook.Worksheets("Sheet1")
    Dim ws2 As Worksheet:   Set ws2 = ThisWorkbook.Worksheets("Sheet2")

    Dim r As Long, ws2val As String

    ws1.Range(RNG).ClearContents

    For r = START_ROW To 30 * OFFSET_ROW + START_ROW - 1 Step OFFSET_ROW

        ws2val = ws2.Cells(Application.RoundUp(Rnd() * 88, 0), "A").Value

        If Application.CountIf(ws1.Range(RNG), ws2val) = 0 Then
            ws1.Range("B" & r).Value = ws2val
        Else
            r = r - OFFSET_ROW
        End If
    Next
End Sub

測試數據在表2,結果為表1
(輸出按照您的預期從第 10 行開始)

表1表2

相關內容