Dim myText As String
myText= Range("a3").Text
返回单元格 A3 中的格式化值,但是
myText= Range("a3:c7").Text
给我一个错误。
如何从多单元格区域获取表示格式化值的字符串,同时保留数字格式?即输出文本的格式与从范围复制粘贴到文本编辑器的格式相同。
最佳答案
使用一个语句(无循环)将多个单元格值放入数组的唯一方法是使用 Variant 数组。
Dim varItemName As Variant
varItemName = Range("a3:c7")
如果您确实需要将名称设置为 String
类型,那么稍后在使用它们时只需使用 CStr
即可。
output = FunctionRequiringStringArgument(CStr(varItemName(1,2))
<小时/>
编辑:好的,好的,您想要与工作表中格式相同的字符串。
这是一个完整的工作示例。
Dim strMyFormat1 As String
Dim varItemName As Variant
Dim strItemName() As String
Dim strItemNameBF() As String
Dim iCol As Long
Dim iRow As Long
Dim rngMyRange As Range
Set rngMyRange = Range("A3:C7")
varItemName = rngMyRange
ReDim strItemName(LBound(varItemName, 1) To UBound(varItemName, 1), _
LBound(varItemName, 2) To UBound(varItemName, 2))
'// Take a sample of the format
strMyFormat1 = Range("A3").NumberFormat
'// Apply format sample to all values
For iRow = LBound(varItemName, 1) To UBound(varItemName, 1)
For iCol = LBound(varItemName, 2) To UBound(varItemName, 2)
strItemName(iRow, iCol) = Format(varItemName(iRow, iCol), strMyFormat1)
Next iCol
Next iRow
'// Can also apply to only some values -- adjust loops.
'// More loops go here if many format samples.
'// If all cells have different formats, must use brute force -- slower.
ReDim strItemNameBF(1 To rngMyRange.Rows.Count, _
1 To rngMyRange.Columns.Count)
For iRow = 1 To rngMyRange.Rows.Count
For iCol = 1 To rngMyRange.Columns.Count
strItemNameBF(iRow, iCol) = rngMyRange.Cells(iRow, iCol).Text
Next iCol
Next iRow
关于vba - 从多单元格区域获取格式化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5590963/