提示输入值,然后复制但添加文本(第2页)

时间:2015-11-09 20:57:38

标签: excel vba excel-vba excel-2010

对于我的请求的第1部分,以下代码帮助我填充了单元格G2:G10

第1部分的链接:Prompt for value, then copy but add text

Sub Set_Tag()

Dim TagName As String
Dim x As Long, TagNum As Long, i As Long, k As Long

TagName = InputBox("What is the product tag name? Ex. Apple", "Tag Name")
TagNum = InputBox("What is the first product tag #?", "1st Tag #")

x = Application.WorksheetFunction.CountIf(Range("J:J"), " ")

With ActiveSheet.Range("G2")
    For i = 1 To x Step 3
        .Item(i + 0) = TagName & "_" & TagNum + k
        .Item(i + 1) = TagName & "_" & TagNum + k & "_T"
        .Item(i + 2) = TagName & "_" & TagNum + k & "_NE"
        k = k + 10
    Next
End With

End Sub

对于第2部分,我需要宏继续使用不同的值填充G列中的值。在上面的示例中,起始单元格位于行x+2G11。我的代码适用于我需要的东西,唯一的东西是G11被硬编码为起始单元格。我想用更符合逻辑的东西替换它,因为它可能不是所有文件的起始单元格。

Sub Set_Tag2()

Dim TagName As String
Dim x As Long, TagNum2 As Long, i As Long, k As Long

TagName = InputBox("What is the product tag name? Ex. Apple", "Tag Name")
TagNum2 = InputBox("What is the second PDW tag #?", "2nd Tag #")

x = Application.WorksheetFunction.CountIf(Range("J:J"), " ")

With ActiveSheet
    LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
End With

With ActiveSheet.Range("G11")
    For i = 1 To LastRow Step 1
        .Item(i + 0) = TagName & "_RED_" & TagNum2 + k
        k = k + 10
    Next
End With

End Sub

因此,如果用户将Apple作为TagName输入,1060作为TagNum2输入,则剩余的单元格将填充如下:

Apple_RED_1060
Apple_RED_1070
Apple_RED_1080

......一直持续到LastRow。有人可以帮助我用更符合逻辑和动态的东西替换With ActiveSheet.Range("G11")吗?

1 个答案:

答案 0 :(得分:0)

我解决了!我将With ActiveSheet.Range("G20")替换为With ActiveSheet.Range("G" & y),其中y = x + 2。这是我的完整宏(无需将其拆分为2个宏):

Sub Set_Tag()

Dim TagName As String
Dim x As Long, y As Long, TagNum As Long, TagNum2 As Long, i As Long, k As Long

TagName = InputBox("What is the product tag name? Ex. Apple", "Tag Name")
TagNum = InputBox("What is the 1st starting tag #?", "1st Tag #")
TagNum2 = InputBox("What is the 2nd starting tag #?", "2nd Tag #")

x = Application.WorksheetFunction.CountIf(Range("J:J"), " ")
y = x + 2

With ActiveSheet
    LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
    z = .Cells(.Rows.Count, "J").End(xlUp).Row
End With

k = 0
With ActiveSheet.Range("G2")
    For i = 1 To x Step 3
        .Item(i + 0) = TagName & "_" & TagNum + k
        .Item(i + 1) = TagName & "_" & TagNum + k & "_T"
        .Item(i + 2) = TagName & "_" & TagNum + k & "_NE"
        k = k + 10
    Next
End With

k = 0
    With ActiveSheet.Range("G" & y)
    For i = 1 To LastRow Step 1
        .Item(i + 0) = TagName & "_RED_" & TagNum2 + k
        k = k + 10
    Next
End With

End Sub