【问题标题】:Loop through selected cells in VB.net循环遍历 VB.net 中的选定单元格
【发布时间】:2015-01-26 07:46:03
【问题描述】:

我刚开始学习 Vb.net。在 VBA 中,我可以像这样遍历选定的单元格并更改选择中所有单元格的大小写

Dim c As Range
For Each c In Selection
    If c.HasFormula = False Then
        c.Value = UCase(c.Value)
    End If
Next

我如何在 VB.Net 中实现这一点,记住我还不知道将选择什么范围的单元格

【问题讨论】:

标签: vb.net excel vba


【解决方案1】:

好的,试试这个。我正在使用DataGridView 为用户提供一些可供选择的单元格。当用户点击“显示选定”按钮时,For Each 循环会遍历每个选定的单元格。

Public Class Form1
Dim gridSelection As New DataGridView
Dim lblSelection As New Label
Dim Selection As String

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'Setup DataGridView
    gridSelection.Columns.Add("columnA", "A")
    gridSelection.Columns.Add("columnB", "B")
    gridSelection.Columns.Add("columnC", "C")
    gridSelection.Columns.Add("columnD", "D")
    gridSelection.Rows.Add(6)
    gridSelection.Location = New Point(0, 0)
    gridSelection.AutoSize = True

    'Setup Button to show Selection
    Dim btnShow As New Button
    btnShow.Text = "Show Selected"
    btnShow.Location = New Point(0, 250)
    btnShow.AutoSize = True
    AddHandler btnShow.Click, AddressOf btnShow_Click

    'Setup label to display Selection
    lblSelection.Text = Nothing
    lblSelection.Location = New Point(0, 300)
    lblSelection.AutoSize = True

    'Add controls to form
    Me.Controls.AddRange({gridSelection, btnShow, lblSelection})
End Sub

Sub btnShow_Click()
    'Reset Selection list.
    Selection = Nothing

    'Loop through each selected cell.
    For Each cell As DataGridViewCell In gridSelection.SelectedCells
        Dim column As String = cell.OwningColumn.HeaderText
        Dim row As String = cell.RowIndex.ToString()

        'Add cell to Selection list.
        Selection = IIf(Selection = Nothing, Selection, Selection + ", ") + column + row
    Next

    'Show Selection list.
    lblSelection.Text = Selection
End Sub
End Class

希望这能为您描绘出更好的画面。

【讨论】:

  • 我知道如何在 Vb.net 中运行基本循环,但我真正需要的是我发布的确切 VBA 代码在 Vb.net 中的样子。将所有当前选定单元格的大小写更改为 UPPER
  • Right c = c.ToUpper 将在 VB.net 中为您执行此操作。抱歉,如果我不理解您的问题。
  • 谢谢@supersnake 让我尝试提供更多详细信息。假设用户选择单元格 A1、C2 和 D3,则可以使用像 For each cell in selection 这样的代码来仅对这些选定的单元格执行操作。如果我要做这个 vb.net,我会怎么做?什么是 vb.net 中的“选择”等价物。我希望这有助于使我的问题更清楚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2012-09-26
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多