简体   繁体   English

Excel VBA 在数字字符串中添加零

[英]Excel VBA Adding Zero in Number String

im only new to vba so i dont really know much about programming, anyway, i created a macro that adds a zero before a single digit string number in my selection, it only works if my selections are single digits only but doesn't work when theres a double digits or more in my selection, this is my code:我只是 vba 的新手,所以我对编程不太了解,无论如何,我创建了一个宏,在我的选择中的单个数字字符串数字之前添加一个零,它仅在我的选择是单个数字时才有效,但在以下情况下不起作用我的选择中有两位数或更多,这是我的代码:

Sub AddZero()
 Dim cell As Range
 
 For Each cell In Selection
  If Not IsNumeric(cell) = False And cell > 10 Then
   Exit Sub
    Else:
   cell = "0" & cell
  End If
 Next
End Sub

How can i make my macro skip all cells with double digits and only target single digits, pls help and thanks very much in advance.我怎样才能让我的宏跳过所有两位数的单元格并且只针对一位数,请提前帮助并非常感谢。

How can i make my macro skip all cells with double digits and only target single digits我怎样才能让我的宏跳过所有具有两位数的单元格并且只针对单个数字

No need for a Loop.不需要循环。 You can achieve what you are doing in 1 line您可以在 1 行中实现您正在做的事情

Selection.NumberFormat = "00"

Also avoid the use of Selection .还要避免使用Selection Try something like this尝试这样的事情

Sub AddZero()
    Dim rng As Range
    
    '~~> Change this to the relevant sheet/range
    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A10")
    
    rng.NumberFormat = "00"
End Sub

BEFORE

在此处输入图像描述

AFTER

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM