vba - 从多单元格区域获取格式化值

标签 vba excel

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/

相关文章:

excel - 根据另一列中的条件计算唯一值

excel - 在 Excel 2007 中创建自删除宏

从 Auto_Open 调用宏时,excel vba HPageBreak.Count 不起作用

VBA:使用公共(public)属性 Get 代替 Const(对于非 Unicode 字符)

vba - 在VBA中使用变量名调用函数

c# - 从 .NET 中的 VBA 函数访问返回值?

Excel最后一个单元格错误

VBA 错误处理和 MZ 工具

excel - 查询在循环内失败(返回 EOF)

java - 用java替换字符串中文本的最佳方法