Excel VBA:将活动单元格变为粗体的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6045826/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:30:47  来源:igfitidea点击:

Excel VBA: function to turn activecell to bold

vbaexcel-vbaexcel-2007excel

提问by Shyam

I have the following function inside my module.

我的模块中有以下功能。

Function Colorize(myValue)
    ActiveCell.Select
    Selection.Font.Bold = True
    Colorize = myValue
End Function

The cell that will use this function should be turning bold - however, I get no error messages back and sad but true, its not turning bold. What am I missing?

将使用此功能的单元格应该变成粗体 - 但是,我没有收到错误消息,悲伤但真实,它没有变成粗体。我错过了什么?

Thanks

谢谢

回答by osknows

A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.

UDF 只会返回一个值,它不允许您更改单元格/工作表/工作簿的属性。将您的代码移动到 Worksheet_Change 事件或类似的更改属性。

Eg

例如

Private Sub worksheet_change(ByVal target As Range)
  target.Font.Bold = True
End Sub

回答by Dev.Jaap

I use

我用

            chartRange = xlWorkSheet.Rows[1];
            chartRange.Font.Bold = true;

to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.

将第一行单元格字体变为粗体。它有效,我也在使用 Excel 2007。

You can call in VBA directly

可以直接在VBA中调用

            ActiveCell.Font.Bold = True

With this code I create a timestamp in the active cell, with bold font and yellow background

使用此代码,我在活动单元格中创建了一个带有粗体和黄色背景的时间戳

           Private Sub Worksheet_SelectionChange(ByVal Target As Range)
               ActiveCell.Value = Now()
               ActiveCell.Font.Bold = True
               ActiveCell.Interior.ColorIndex = 6
           End Sub