我做错了什么? VBA如果这和这就是这个

我真的需要帮助

我试图让这个代码正确。 我需要把一个邮政编码0。 只有在不是空的单元格和小于5的单元格。

For i = 2 To ende2 If (Not IsEmpty(LTrim(Cells(i, 9).Value))) And Len(LTrim(Cells(i, 9).Value)) < 5 Then Cells(i, 9).Value = "0" & Cells(i, 9).Value End If next i 

代码返回一个0的邮政编码..但是也把一个0空的单元格..为什么?

林新编程..所以请不要对我难:P

感谢您的帮助:)

LG Madosa

即使它仍然是一个零长度的string, LTrim会使值非空。 尝试这个:

 If (Not IsEmpty(Cells(i, 9))) And Len(LTrim(Cells(i, 9).Value)) < 5 Then 

顺便说一句,如果你试图添加一个零的值是数字,程序将没有结果。 您将需要将单元格格式更改为文本。 把这个放在If行后面:

 Cells(i, 9).NumberFormat = "@" 

你不需要代码。

假设邮编在列A中,将此公式添加到列B.

 =IF(A1<>"","0"&A1,"") 

下面的故障解释。

 ' Checks the cell in A1 for something =IF(A1<>"", ' If there is, concatenate a "0" and whatever is in A1 "0"&A1, ' Otherwise put an empty string. "") 

然后可以复制列B,然后select“编辑”>“select性粘贴”>“值”将公式转换为文本。

ALT + E,然后S,然后V,然后单击确定。

虽然这段代码更长,但会更快

  • 忽略开始的空单元格(使用Set rng1 = Selection.SpecialCells(xlConstants, xlNumbers)
  • 它使用变体数组

 Sub AddLeadingZeros() Dim rng1 As Range Dim rngArea As Range Dim strRep As String Dim lngRow As Long Dim lngCol As Long Dim lngCalc As Long Dim X() strRep = "'0" On Error Resume Next 'Set rng1 = Application.InputBox("Select range for the replacement of leading zeros", "User select", Selection.Address, , , , , 8) Set rng1 = Selection.SpecialCells(xlConstants, xlNumbers) If rng1 Is Nothing Then Exit Sub On Error GoTo 0 'Speed up the code by turning off screenupdating and setting calculation to manual 'Disable any code events that may occur when writing to cells With Application lngCalc = .Calculation .ScreenUpdating = False .Calculation = xlCalculationManual .EnableEvents = False End With 'Test each area in the user selected range 'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on For Each rngArea In rng1.Areas 'The most common outcome is used for the True outcome to optimise code speed If rngArea.Cells.Count > 1 Then 'If there is more than once cell then set the variant array to the dimensions of the range area 'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks X = rngArea.Value2 For lngRow = 1 To rngArea.Rows.Count For lngCol = 1 To rngArea.Columns.Count 'add leading zeroes If Len(X(lngRow, lngCol)) < 5 Then X(lngRow, lngCol) = strRep & X(lngRow, lngCol) Next lngCol Next lngRow 'Dump the updated array swith a leading zeroes back over the initial range rngArea.Value2 = X Else 'caters for a single cell range area. No variant array required If (Len(rngArea.Value) < 5) Then rngArea.Value = strRep & rngArea.Value2 End If Next rngArea 'cleanup the Application settings With Application .ScreenUpdating = True .Calculation = lngCalc .EnableEvents = True End With End Sub