excel - 将当前选定的单元格设置为要处理的范围
问题描述
我正在使用 Visual Studio 构建一个 Excel 插件并将我的 Excel VBA 代码转换为 VB.Net 代码。
我无法弄清楚如何通过在 Excel 中选择的单元格上的插件运行宏。
此代码在单元格 A1 上执行。如何将其更改为适用于所有选定的单元格?
Imports Microsoft.Office.Tools.Ribbon
Imports Microsoft.Office.Interop.Excel
Public Class Ribbon1
Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load
End Sub
Private Sub BtnFontToggle_Click(sender As Object, e As RibbonControlEventArgs) Handles BtnFontToggle.Click
Dim ActiveWorksheet As Microsoft.Office.Interop.Excel.Worksheet =
Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets(1)
Dim Worksheet As Microsoft.Office.Tools.Excel.Worksheet =
Globals.Factory.GetVstoObject(ActiveWorksheet)
Dim CurrentColor
Dim Selection As Excel.Range = Worksheet.Range("A1")
'******* Instead of selecting cell A1, I want the code to select all active cells (those that are currently highlighted)*****
'What is the current font color?
CurrentColor = Selection.Font.ColorIndex
'Change font color based on current font color
'Order Black, Blue, Green, Red
If CurrentColor = 1 Then
Selection.Font.ColorIndex = 5
Else
If CurrentColor = 5 Then
Selection.Font.ColorIndex = 10
Else
If CurrentColor = 10 Then
Selection.Font.ColorIndex = 3
Else
If CurrentColor = 3 Then
Selection.Font.ColorIndex = 1
Else
Selection.Font.ColorIndex = 1
End If
End If
End If
End If
End Sub
End Class
解决方案
您应该能够使用Application.Selection 属性来确定当前是否选择了 Excel.Range,如果是,则检索它。请注意,当前选择可能是其他对象,例如 ChartArea。Selection 属性返回 type Object
,因此用于TryCast
尝试转换为Excel.Range
. 如果转换失败,则TryCast
返回Nothing
。
Dim Selection As Excel.Range = TryCast(Globals.ThisAddIn.Application.Selection, Excel.Range)
If Selection IsNot Nothing Then
' you retrieved a Range object
End If
推荐阅读
- java - 升级到 Spring Boot 2.2 后 Springboot WebFlux 测试失败
- python - 如何将“for循环”转换为“递归”?
- jquery - 如何使用 laravel 中的 @included 在引导模型中编辑表单
- excel - Excel VBA - 将行复制并粘贴到新的空白行,从预定义的位置开始
- android - 如何为 MongoDB Atlas 中的每个设备建立单一连接?
- c# - C# - 将用户批量添加到 AD 组时出现问题
- python - Python discord bot 跳过代码或停止工作
- python - 运行 sys.meta_path[2].find_distributions() 时出现 Python OSError(pytest 需要)
- mongodb - Mongodb 使用嵌套查找聚合复杂文档
- vue.js - VueJS 前端/管理屏幕