excel - 如何复制单元格格式和样式

标签 excel vba object cell-formatting

伙计们,如果我使用以下代码:

dim Defaultcol As Long

Defaultcol = Sheets("Whatever").Cells(1, 1).Interior.Color

我可以从单元格中获取颜色格式。

我也可以写类似的东西吗
dim FullFormat as object (Or dim FullFormat as cellformat)

set FullFormat =  Sheets("Whatever").Cells(1, 1).formats

并在一个对象中获取单元格的所有格式?

或者可能
dim sourcecell as cell

set sourcecell = Sheets("Whatever").Cells(1, 1)

然后拥有属性(property)sourcecell.formats我可以用吗?

提前致谢。

最佳答案

有一种方法可以使用 MSND's Guide 复制单元格的基本格式。

虽然上述可能是 VBA 的解决方法,但没有直接复制单元格样式/格式的方法。

确实 Style object存储样式但不存在允许您使用 Style 的方法(至少我不知道有任何方法)对象以在单元格之间复制和应用格式。

有一个使用 VBA 的解决方法

一种方法是使用 String要复制的参数fromto IE。

Private Sub CopyFormatting(fromRng As String, toRng As String)
Application.ScreenUpdating = False
    Dim tmpVal
    tmpVal = Range(toRng)
    Range(fromRng).Copy Range(toRng)
    Range(toRng) = tmpVal
Application.ScreenUpdating = True
End Sub

并称它为
Sub Main()
    CopyFormatting "A1", "A10"
End Sub

这将复制格式并保留值,这与许多仅复制和粘贴单元格的在线指南不同

更好的方法是传递对 Range 的引用对象,因为您可以在不同的工作表等之间使用它。

例子
Option Explicit

Sub Main()
    Dim rng1 As Range, rng2 As Range
    Set rng1 = Sheets(1).Range("B3")
    Set rng2 = Sheets(2).Range("A1")

    CopyFormatting rng1, rng2
End Sub

Private Sub CopyFormatting(fromRng As Range, toRng As Range)
Application.ScreenUpdating = False
    Dim tmpVal
    tmpVal = toRng
    fromRng.Copy toRng
    toRng = tmpVal
Application.ScreenUpdating = True
End Sub

关于excel - 如何复制单元格格式和样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350676/

相关文章:

javascript - 自定义对象上的 addEventListener

Excel VBA 文件由同一用户与其他用户打开

java - 如何使用集合在java中按对象分组?

ruby - Ruby 的 "hello world"中的对象是什么?

vba - 导入代码行

excel - 从命令行或批处理文件运行 Excel 宏的方法?

excel - 定义范围并清除其内容

excel - 逐行自动计算不同数值的平均值

.net - Excel VBA 网页抓取 - 自动化错误/未指定错误

c++ - 如何读取没有换行符 CRLF "\r\n"的 CSV 记录?