本文介绍了Excel VBA不会保持领先的零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找不到一种在VBA代码中保存前导零的方法。零是必需的,因为它们对应于唯一ID。

I can't seem to find a way to save leading zeros in my VBA code. The zeros are necessary since they correspond to unique IDs.

我已经尝试将数字格式更改为文本和0000 ....在excel和我的实际代码中相同的方法:
ActiveSheet.Cells(我,j).NumberFormat =00000

I've tried changing the number format to text and 0000.... in excel and the same approach in my actual code: ActiveSheet.Cells(i, j).NumberFormat = "00000"

其他任何建议? (如果我将这些数字手动输入到VBE中,它也会剥离前导零)。
编辑:

Any other suggestions? (If I manually type these numbers into VBE it strips the leading zeros too).

Sheets.Add.Name = "Temp"
Sheets("Sheet1").Select
ActiveSheet.Cells(2, 2).NumberFormat = "000"
cid = Cells(2, 2)
MsgBox cid
Sheets("Sheet2").Select
ActiveSheet.Cells(6, 1).NumberFormat = "00000"
sid = Cells(6, 1)
Sheets("Temp").Select
Url = _
"URL;" & _
"http......asp?" & _
"X1=" & cid & "&" & _
"X2=" & sid & "&"

这是最后一个循环,但是我作为单独的迭代调试。

This is inside a loop ultimately but I'm debugging as individual iterations.

推荐答案

以下所有讨论都是将写入单元格,而不是从单元读取。更改数字格式不会这样工作。
看看你可以弄清楚这段代码如何工作:

All below deliberations were about writing to a cell, not reading from it. Changing the Numberformat doesn't work that way.See if you can figure out how this code works:

dim v as integer
v = val(Sheets("Sheet1").Cells(2, 2))
dim cid as string
cid = format(v, "000")

您不应该使用选择 ActiveSheet , 没有必要;并且不要使用单元格而不使用它应该引用的工作表。

Val 可以

You should never use Select and ActiveSheet that way, it is not necessary; and never use Cells without the sheet it should be referring to.
(Val can be omitted if the cell is really already numeric and not text).

以前的答案...:

此代码对我来说非常适用

This code works perfectly fine for me

Worksheets(1).Columns("A").NumberFormat = "@"
Worksheets(1).Cells(1, "A").Value = "00023"

还有

Worksheets(1).Columns("A").NumberFormat = "000000"
Worksheets(1).Cells(1, "A").Value = "0023"

(这里的字符串转换为一个数字并显示6位数字)

(Here the string is converted to a number and displayed with 6 digits)

编辑:

如果失败 - 虽然我不能解释 - 我还是认为,'应该真的工作:

(不需要数字格式。 )


If that fails - although I could not explain that - I'd still bet that the ' should really work:
(No numberformat required.)

Dim s As String
s = "0002"
Worksheets(1).Cells(1, "A").Value = "'" & s

这篇关于Excel VBA不会保持领先的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:30