为复制的数据创建由Year + Month + Number组成的唯一标识符

时间:2017-12-21 15:59:17

标签: excel vba excel-vba

大家好。对于每个循环,我将数据复制到摘要表中:

For Each sheet_name In Sheets("Frontend").Range("L21:L31")
Set ws = Worksheets(sheet_name.Text)

 For ZeileUntersucht = 20 To 515
    If ws.Cells(ZeileUntersucht, 238).Value = "yes" Then
        Worksheets("Market Place Output").Cells(ZeileEintragen, 3) = 
ws.Cells(ZeileUntersucht, 1)
        Worksheets("Market Place Output").Cells(ZeileEintragen, 4) = 
ws.Cells(ZeileUntersucht, 240)
        Worksheets("Market Place Output").Cells(ZeileEintragen, 6) = 
ws.Cells(ZeileUntersucht, 11)
        Worksheets("Market Place Output").Cells(ZeileEintragen, 7) = 
ws.Cells(ZeileUntersucht, 10)
        Worksheets("Market Place Output").Cells(ZeileEintragen, 9) = 
ws.Cells(ZeileUntersucht, 4)
        Worksheets("Market Place Output").Cells(ZeileEintragen, 2) = ws.Name
        Worksheets("Market Place Output").Cells(ZeileEintragen, 8) = "EUR"
        Worksheets("Market Place Output").Cells(ZeileEintragen, 10) = Date + 
Time
        ZeileEintragen = ZeileEintragen + 1


    End If
Next ZeileUntersucht

Next sheet_name

我想在第一列中添加一个看起来像这样的唯一标识符 2017510001.所以年+周+ 0001,然后在有数据的每一行向上计数。

这是我到目前为止所做的:

n = 1
For i = 11 To LastRow
    If  Then
     n = n + 1
    End If
 Next i

 txtCount = Format(n, "00")

'Create ID Number'

IDnum = " " & txtYear & "" & txtMonth & "-" & txtCount & ""

但是我遇到了如何将ID实际输入到A列并仅用数据填充行的问题。

如果您需要进一步澄清,请询问。

编辑:我现在的功能如下:

Sub MacroToDoTheWork()

Dim ws As Worksheet
Dim sheet_name As Range
Dim txtYear As String
Dim txtWeek As String
Dim txtCount As String
Dim LastRow As Long
Dim i As Long
Dim D As Date

'Define Variables 
txtYear = Format(D, "yyyy")
txtWeek = Format(D, "ww")

'Unique Identifier
LastRow = Worksheets("Market Place Output").Cells(Worksheets("Market Place Output").Rows.Count, "B").End(xlUp).Row
For i = 2 To LastRow
    txtCount = Format(i - 1, "0000")
    Worksheets("Market Place Output").Cells(i, 1).Value = txtYear & txtWeek & txtCount
Next i

End Sub

这是以下标识符的输出: 1899520001而不是2017510001

这让我相信它实际上存储了日期31.12.1899而不是当前日期。这是我面临的当前问题。

2 个答案:

答案 0 :(得分:1)

尝试:

Dim i As Long, j As Long, k As String
'This would be where your other code sits, including Dim for LastRow
j = 1
For i = 11 To LastRow
    k = Format(j, "0000")
    Cells(i, 1).Value = "'" & txtYear & "" & txtMonth & k
    j = j + 1
    k = ""
Next i

我将此匹配作为您给出的示例,其输出为(今天的第一项) 2017120001

答案 1 :(得分:1)

如果您希望将其添加到工作表的A列("市场输出"),那么这将为您做到(假设您有标题,并且txtYear和txtMonth已经有一些数据)它们):

Sub foo()
LastRow = Worksheets("Market Place Output").Cells(Worksheets("Market Place Output").Rows.Count, "B").End(xlUp).Row
txtYear = Format(Date, "yyyy")
txtWeek = Format(Date, "ww")
For i = 2 To LastRow
    txtCount = Format(i - 1, "0000")
    Worksheets("Market Place Output").Cells(i, 1).Value = txtYear & txtWeek & txtCount
Next i
End Sub