创建多个模板

时间:2018-03-13 16:31:40

标签: vba excel-vba excel

我有下面的宏,它从模板文件创建多个模板,并根据示例文件更改值。该列中有一些空白单元格。我希望VBA跳过这些列并转到下一列。下面的宏运行正常,但不要跳过空白单元格。知道如何让它更好吗?

Sub Template()

Dim i As Long, N As Long, A As Variant, B As Variant, j As Long
N = Range("P9999").End(xlUp).Row

j = 5

For i = 1 To N

   If Cells(j, 16).Value = "" Then
            j = j + 1
            Else: j = j
            End If
    Sheets("Template").Copy after:=Sheets(Sheets.Count)
   A = Sheets("RR9 Sample ").Range("P" & j).Value
   B = Sheets("RR9 Sample ").Range("O" & j).Value
    ActiveSheet.Range("E9").Value = A
    ActiveSheet.Range("E10").Value = B

j = j + 1
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

你可能在此之后

Sub Template()

    Dim j As Long
    Dim cell As Range

    j = 5
    With Sheets("RR9 Sample")
        For Each cell In .Range("P1", .Cells(.Rows.Count, "P").End(xlUp))
            If cell.value <> "" Then
                j = j + 1
                Sheets("Template").Copy after:=Sheets(Sheets.Count)
                ActiveSheet.Range("E9").value = cell.value
                ActiveSheet.Range("E10").value = cell.Offset(, -1).value
            End If
        Next i
    End With
End Sub

或者,您可以使用SpecialCells对象

Range方法
Sub Template()
    Dim j As Long
    Dim cell As Range

    j = 5
    With Sheets("RR9 Sample")
        For Each cell In .Range("P1", .Cells(.Rows.Count, "P").End(xlUp)).SpecialCells(xlCellTypeConstants)
            j = j + 1
            Sheets("Template").Copy after:=Sheets(Sheets.Count)
            ActiveSheet.Range("E9").value = cell.value
            ActiveSheet.Range("E10").value = cell.Offset(, -1).value
        Next i
    End With
End Sub