热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ExcelVBA-以0开头的字符串-ExcelVBA-Stringsstartingwith0

DimtesttextAsStringtesttextWorksheets(Sheet2).Range(B6).ValueWorksheets(Sheet2).Range(
Dim testtext As String
testtext = Worksheets("Sheet2").Range("B6").Value
Worksheets("Sheet2").Range("B7").Value = testtext

Simple copying of one cell's content into another. But I run into problems when content of B6 is '02345 - after running the macro B7 contains 2345 and I don't want to lose the leading zero. I tried replacing .Value with .Text in second line of the code and this didn't help.

将一个单元格的内容简单复制到另一个单元格中。但是当B6的内容为'02345时,我遇到了问题 - 在运行宏B7包含2345之后,我不想失去前导零。我尝试在代码的第二行用.Text替换.Value,这没有帮助。

4 个解决方案

#1


9  

If you change the .NumberFormat property to "@", it will write 02345 in the cell.

如果将.NumberFormat属性更改为“@”,它将在单元格中写入02345。

Dim testtext As String
testtext = Worksheets("Sheet2").Range("B6").Value
Worksheets("Sheet2").Range("B7").NumberFormat = "@"

Worksheets("Sheet2").Range("B7").Value = testtext

This works because the standard cell format reads a number with leading 0s as a numeric value, and therefore the leading 0s are removed. By forcing Excel to use the text format on that particualar cell, it will not treat it as a numeric value, but just as plain text.

这是因为标准单元格格式读取带有前导0的数字作为数值,因此删除了前导0。通过强制Excel在该特定单元格上使用文本格式,它不会将其视为数值,而是将其视为纯文本。

#2


4  

I don't know what is the default property of Range, but anyway

我不知道Range的默认属性是什么,但无论如何

With Worksheets("Sheet2")
  .Range("B7") = .Range("B6")
End With

seems to work perfectly.
If you really need the intermediate testext variable, I would rather define it as Variant.

似乎完美无缺。如果你真的需要中间的testext变量,我宁愿把它定义为Variant。

#3


2  

Try simple copying of one cell's content into another with copy method.

尝试使用复制方法将一个单元格的内容简单复制到另一个单元格中。

   Worksheets("Sheet2").Range("B6").copy Worksheets("Sheet2").Range("B7")

#4


1  

You could use the FormulaR1C1 property of a cell to insert the single quote which causes Excel to interpret it as text. This mimics what actually happens when you enter '02345 in the B6 originally, as you can verify by doing so with the macro recorder turned on:

您可以使用单元格的FormulaR1C1属性插入单引号,这会导致Excel将其解释为文本。这模仿了最初在B6中输入'02345时实际发生的情况,因为您可以通过打开宏录制器来验证:

Worksheets("Sheet2").Range("B7").FormulaR1C1 = "'" & testtext

推荐阅读
author-avatar
骷髅怪天堂_821
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有