在不同的工作表中按列循环

时间:2016-12-12 21:01:59

标签: excel vba excel-vba macros

我有一个宏需要根据工作表“NSA”中存在的列数进行循环(不计算日期),如下图所示:

enter image description here

循环遍历列,宏需要使用随机数填充工作表“SA”中的相应范围,一次一列。

我希望每次在“NSA”中发生循环时填充一列“SA”,以便在B:B和C:C中保留不同的数字。

因此,在第一次运行代码时,我想仅在B列中插入数据,并在第二次只填充C列。

这就是我的代码失败的地方。每次运行时,它总是同时填充工作表“SA”中的B列和C列。这是我得到的(对于随机值): enter image description here

根据“NSA”中的循环,如何更改循环以使“SA”中的列一次只更改一个?

感谢您的帮助。

这是我的代码:

Sub Dessaz2()

Dim wb1 As Workbook
Set wb1 = ActiveWorkbook

Dim wsNSA As Worksheet
Set wsNSA = wb1.Worksheets("NSA")

Dim wsSA As Worksheet
Set wsSA = wb1.Worksheets("SA")

Dim col1 As Range
Dim col2 As Range

LR = wsNSA.Cells(3, 1).End(xlDown).Row
LC = wsNSA.Cells(3, 1).End(xlToRight).Column


For Each col1 In wsNSA.Range(Cells(3, 2), Cells(LR, LC)).Columns
wsNSA.Activate


wsSA.Activate

x = WorksheetFunction.RandBetween(0, 100)
wsSA.Range(Cells(3, 2), Cells(LR, LC)) = x

Next

End Sub

2 个答案:

答案 0 :(得分:0)

每次填写col1.column:

Sub Dessaz2()

Dim wb1 As Workbook
Set wb1 = ActiveWorkbook

Dim wsNSA As Worksheet
Set wsNSA = wb1.Worksheets("NSA")

Dim wsSA As Worksheet
Set wsSA = wb1.Worksheets("SA")

Dim col1 As Range
Dim col2 As Range

LR = wsNSA.Cells(3, 1).End(xlDown).Row
LC = wsNSA.Cells(3, 1).End(xlToRight).Column


For Each col1 In wsNSA.Range(wsNSA.Cells(3, 2), wsNSA.Cells(LR, LC)).Columns
wsNSA.Activate


wsSA.Activate

x = WorksheetFunction.RandBetween(0, 100)
wsSA.Range(wsSA.Cells(3, col1.Column), wsSA.Cells(LR, col1.Column)) = x

Next

End Sub

答案 1 :(得分:0)

Sub Main()
    Dim rng as Range, cl as Range

    Set rng = worksheets("NSA").Range("B1:C100")  // update for your Range

    For each cl in rng
        Worksheets("SA").Range(cl.Address) = WorksheetFunction.RandBetween(0, 100)
    Next cl
End Sub