簡體   English   中英

如何獲取 VBA 范圍內第一個非空白單元格的列字母?

[英]How to get the column letter of the first non blank cell of a range in VBA?

我需要獲取范圍的第一個非空白單元格的列字母。 這個范圍基本上是一行的一部分。

示例:范圍 = A2:G2 第一個非空白單元格位於 F2 單元格上。 需要獲取 'F' 並將其存儲在 String 變量中。 得到這個的最有效方法是什么?

謝謝

嘗試這個:

Sub columnName()
    Dim mainRange As Range, cell As Range, columnName As String
    Set mainRange = Range("A2:G2")
    'Set mainRange = Selection
    For Each cell In mainRange.Cells
        If Not IsEmpty(cell.Value) Then
            MsgBox Split(cell.Address, "$")(1)
            Exit For
        End If
    Next cell
End Sub

您可以使用 function 獲得該列字母:

Function firstBlankCol(rg As Range) As String
Dim x
    If rg(1) = "" Then
        x = rg(1).Address
    Else
        x = rg(1).End(xlToRight).Offset(0, 1).Address
    End If
    firstBlankCol = Split(x, "$")(1)
End Function

但是,通常更簡單的是處理列號,並將其用於Cells屬性的列參數。

Function firstBlankCol(rg As Range) As Long
Dim x
    If rg(1) = "" Then
        x = rg(1).Column
    Else
        x = rg(1).End(xlToRight).Column + 1
    End If
    firstBlankCol = x
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM