试图提取名字和姓氏的首字母以及形成ID号的数字

问题描述 投票:0回答:1

我正在尝试在excel vba中执行此操作,并且对于所有用户ID,它始终使用该列中的姓氏和姓氏。还尝试在F列中写入用户ID。

Sub User()

Columns("F").Insert Shift:=x1ToLeft 'Inserts a column in between F and E
[F1].Value = "User ID"

Dim Number As String
Dim initial_1 As String
Dim initial_2 As String
Dim cell As Range
Dim txt As String

Dim x As Integer
NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count

Range("A2").Select

For x = 1 To NumRows

For Each cell In Range("B2:B1001")
txt = cell.Value
initial_1 = Left(txt, 1)
Next cell

For Each cell In Range("C2:C1001")
txt = cell.Value
initial_2 = Left(txt, 1)
Next cell

For Each cell In Range("E2:E1001")
txt = cell.Value
Number = Left(txt, 4)
cell.Range("B1") = initial_1 & initial_2 & Number
Next cell

Next

End Sub
excel vba
1个回答
1
投票

您的for循环不正确。您的代码:

For x = 1 To NumRows

For Each cell In Range("B2:B1001")
txt = cell.Value
initial_1 = Left(txt, 1)
Next cell

For Each cell In Range("C2:C1001")
txt = cell.Value
initial_2 = Left(txt, 1)
Next cell

For Each cell In Range("E2:E1001")
txt = cell.Value
Number = Left(txt, 4)
cell.Range("B1") = initial_1 & initial_2 & Number
Next cell

Next

让我们仔细考虑一下。

迭代1:

  1. x=1,因为那是第一个循环的开始。
  2. 我们现在遍历B2:B1001中的每个单元格2a。现在,我们在B列中的此循环中,并将initial_1设置为单元格B2中的第一个字符。2b。我们只是迭代到该范围内的下一个单元格,因此B3。我们将initial_1设置为B3中的第一个字母。2c。我们只是迭代到该范围内的下一个单元格,因此B4。我们将initial_1设置为B4中的第一个字母。...2LAST。最后,将其放入单元格B1001,并将initial_1设置为B1001中的第一个字母。
  3. 在所有循环之后,我们现在将通过列C进行相同的循环。3a。现在,我们在C列中的此循环内,并将initial_2设置为单元格C2中的第一个字符。...3LAST。最后,我们将其保存到C1001,并将单元格C1001的第一个字母存储到Initial_2
  4. 现在通过E列执行相同的循环(您知道了)4a。现在,我们将initial_1 & initial_2 & Number写入B14b。现在,我们将initial_1 & initial_2 & Number写入B1(请注意,这些变量中的值没有更改,因为我们在点击4之前已经进行了这些循环)...4LAST。我们现在将initial_1 & initial_2 & Number写入B1
  5. [现在,我们迭代到X=2,然后再次进行所有这些操作...这就是我们刚刚采取的相同步骤,这意味着我们无所事事地做了很多工作。

相反,循环一次,并在1循环中执行所有此逻辑。

Sub User()

Columns("F").Insert Shift:=x1ToLeft 'Inserts a column in between F and E
[F1].Value = "User ID"

Dim Number As String
Dim initial_1 As String
Dim initial_2 As String    
Dim txt As String

Dim x As Integer
NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count



For x = 2 To NumRows
    initial_1 = Left(Range("B" & x).value, 1)
    initial_2 = Left(Range("C" & x).value, 1)
    Number = Left(Range("E" & x).value, 4)
    txt = Range("E" & x).value 

    'Now write this somewhere (surely not B1 over and over again) I'm guessing column F
    Range("F" & x).value = initial_1 & initial_2 & Number
Next


End Sub

这是相同的逻辑,但不必在周围附加太多变量:

Sub User()    
    Columns("F").Insert Shift:=x1ToLeft 'Inserts a column in between F and E
    [F1].Value = "User ID"      

    Dim x As Integer
    NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count

    For x = 2 To NumRows
        Range("F" & x).value =  Left(Range("B" & x).value, 1) & Left(Range("C" & x).value, 1) & Left(Range("E" & x).value, 4)           
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.