VBA左function不按计划工作

我试图使用左function获得部分帐户代码,但它似乎没有按照我想要的方式工作。 我所有的数据都在名为代码的工作表中。 我在列B中有帐户名称和列C中的帐户代码,并且我想填充A列中的父代码。

现在代码工作,除非代码是0001-xx-xx,它在列A中填充为1而不是0001.有没有办法修复它,所以它显示0001或0022等? 当我在Excel中input公式时,它会显示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 

要坚持你的方法,你可以在公式中添加一个撇号,这样就可以将数字格式化为文本,而不是删除前导零:

 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 

您需要将格式更改为文本:

 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