-1

I need to extract 1st letter from cell B2 concatenate with cell C2 paste in cell A2, then move to next row and repeat till last data row.

I have the following, which partially works, but only works for the first row A2 then fills down this one string through all the rows till last data row.

Sub UserName()

Dim rng As range
Dim lastRow As Long

With Sheets("sheet1")
    lastRow = .range("E" & .Rows.Count).End(xlUp).Row
End With

For Each rng In Sheets("Sheet1").range("A2:A" & lastRow)
    rng.Value = fUserName(rng.Value)
Next
End Sub

The function

Function fUserName(ByVal strUserName As String) As String

Dim r As String

r = range("B2").Select
strUserName = Left(Trim(r), 1) & " " & range("C2")

fUserName = strUserName
End Function
4

6 回答 6

3

恕我直言,您不需要VBA。只需使用公式A2

=CONCATENATE(LEFT(B2, 1),C2)

然后为所有包含数据的单元复制它。

于 2013-05-20T03:55:29.593 回答
2

试试下面的代码。我已经结合了你的程序。 无需使用函数,无需 For each 循环

Sub UserName()

    Dim lastRow As Long

    With Sheets("sheet1")
        lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    End With

    Range("A1:A" & lastRow).FormulaR1C1 = "= left(RC[1],1) & RC[2]"

End Sub
于 2013-05-20T05:05:03.513 回答
1

您的函数是错误的,您将 strUserName 传递给函数,然后在函数中设置相同的变量,但是问题的真正根源是您在函数中使用静态引用,因此您的子例程是哪个单元格无关紧要处理函数看起来像一个单元格 B2 和 C2。

我会一起摆脱这个功能,只替换这条线

rng.Value = fUserName(rng.Value)

rng.Value = Left(Trim(rng.offset(0,1)), 1) & " " & rng.offset(0,2)

如果你真的想使用一个函数,你需要将范围传递给函数,而不是活动单元格的值,因为这与它周围其他单元格的值无关。

于 2013-05-20T03:57:24.717 回答
1

您需要将范围传递给函数:

Sub UserName()

Dim rng As range
Dim lastRow As Long

With Sheets("sheet1")
    lastRow = .range("E" & .Rows.Count).End(xlUp).Row
End With

For Each rng In Sheets("Sheet1").range("A2:A" & lastRow)
    rng.Value = fUserName(rng)
Next

End Sub

Function fUserName(rn as Range) As String  
    fUserName = Left(Trim(rn(1,2).value), 1) & " " & rn(1,3).value
End Function
于 2013-05-20T10:01:37.757 回答
0

很明显 B2 和 C2 是硬编码的值,所以它们不会改变。例如,您需要使用范围对象进行这些更改。这是我要做的伪代码。我让您自己进行必要的调整以使其正常工作(因为我在您的问题中没有看到太多的努力)。

Function fUserName(rng as Range) as String
    fUserName = Left(Trim(rng.Offset(0, 1).value), 1) & " " & rng.Offset(0, 2).value
End Function

而不是调用fUserName()with rng.value,只需输入rng。这将使用范围对象来获取 B 和 C 的正确行。

于 2013-05-20T03:55:16.887 回答
-1

以下代码选择第一个空白行

Sub SelFrstBlankRow()
Dim r1 As Range, r2 As Range, r3 As Range
Set r1 = Sheets("Sheet1").Range("a20")
Set r2 = Sheets("Sheet1").Range("u20")
Set r3 = Range(r1.End(xlUp), r2.End(xlUp)) 'r3 is the 1st blank row
r3.Select

End Sub
于 2014-07-31T16:02:15.630 回答