使用 VBA 将文本添加到 Excel 中的单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20612415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding text to a cell in Excel using VBA
提问by Phil
I've been working with SQL and Excel Macros, but I don't know how to add text to a cell.
我一直在使用 SQL 和 Excel 宏,但我不知道如何向单元格添加文本。
I wish to add the text "01/01/13 00:00"
to cell A1
. I can't just write it in the cell because the macro clears the contents of the sheet first and adds the information afterwards.
我希望将文本添加"01/01/13 00:00"
到单元格A1
。我不能只在单元格中写它,因为宏会先清除工作表的内容,然后再添加信息。
How do I do that in VBA?
我如何在 VBA 中做到这一点?
回答by Bathsheba
Range("$A$1").Value = "'01/01/13 00:00"
will do it.
Range("$A$1").Value = "'01/01/13 00:00"
会做的。
Note the single quote; this will defeat automatic conversion to a number type. But is that what you reallywant? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
注意单引号;这将阻止自动转换为数字类型。但这真的是你想要的吗?另一种方法是格式化单元格以采用日期时间值。然后从字符串中删除单引号。
回答by Floris
You could do
你可以做
[A1].Value = "'O1/01/13 00:00"
if you really mean to add it as text(note the apostrophe as the first character).
如果您真的想将其添加为文本(注意撇号作为第一个字符)。
The [A1].Value
is VBA shorthand for Range("A1").Value
.
该[A1].Value
是VBA的简写Range("A1").Value
。
If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):
如果你想输入一个日期,你可以这样做(感谢@SiddharthRout 编辑订单):
[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")
回答by Garry
You need to use Range
and Valu
e functions.Range
would be the cell where you want the text you wantValue
would be the text that you want in that Cell
您需要使用Range
和Valu
e 函数。Range
将是您想要文本的单元格Value
将是您想要在该单元格中的文本
Range("A1").Value="whatever text"
回答by Neha Kalani
You can also use the cell property.
您还可以使用 cell 属性。
Cells(1, 1).Value = "Hey, what's up?"
Make sure to use a .
before Cells(1,1).Value
as in .Cells(1,1).Value
, if you are using it within With
function. If you are selecting some sheet.
如果您在函数中使用它,请确保.
在Cells(1,1).Value
in之前.Cells(1,1).Value
使用它With
。如果您正在选择一些工作表。