我试图使用左侧功能获取部分帐户代码,但似乎它没有按照我想要的方式工作。我的所有数据都在名为Codes的工作表中。我在B栏和B栏中有帐户名C列中的帐户代码,我想填充A列中的父代码。
现在代码工作,除非代码是0001-xx-xx,它在A列填充为1而不是0001.有没有办法解决它所以它显示0001或0022等?当我在excel中键入公式时,它将显示0002或0022.所以我想使用vba实现此目的。
Dim lLastRow As Long
With Sheets("Codes")
lLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
With .Range("A5:A" & lLastRow)
.FormulaR1C1 = "=LEFT(RC[2],4)"
.Value = .Value
End With
End With
答案 0 :(得分:1)
要坚持使用您的方法,您可以在公式中添加撇号,以便将数字格式化为文本而不删除前导零:
Dim lLastRow As Long
With Sheets("Codes")
lLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
With .Range("A5:A" & lLastRow)
.FormulaR1C1 = "= ""'"" &LEFT(RC[2],4)"
.Value = .Value
End With
End With
虽然单元格中不会显示撇号,但它仍然存在。如果这会导致问题,那么您可以使用这种方法:
Sub foo()
Dim lLastRow As Long
Dim arrCodes() As Variant
Dim rng As Range
Dim i As Integer
With Sheets("Codes")
lLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rng = .Range("C5:C" & lLastRow)
arrCodes = rng
arrCodes = Application.Transpose(arrCodes)
For i = LBound(arrCodes) To UBound(arrCodes)
arrCodes(i) = Left(arrCodes(i), 4)
Next i
Set rng = .Range("A5")
Set rng = rng.Resize(UBound(arrCodes), 1)
rng.NumberFormat = "@"
rng.Value = Application.Transpose(arrCodes)
End With
End Sub
答案 1 :(得分:0)
您需要将格式更改为文字:
Dim lLastRow As Long
With Sheets("Codes")
lLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
With .Range("A5:A" & lLastRow)
.NumberFormat = "@"
.FormulaR1C1 = "=LEFT(RC[2],4)"
.Value = .Value
End With
End With