[英]Find and select first blank cell in column B with Excel vba
以下代碼可以很好地找到給定列(此處為B列)中的第一個空單元格。 但是我需要的是找到該列第一個空白單元格的代碼。
Sub macro1()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 2 'column B has a value of 2
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Select
End If
Next
End Sub
另外,它應該從第10行而不是第1行開始查找。
有人可以重寫此代碼來做到這一點嗎?
您想要的是這樣的東西嗎?
Sub test()
Dim ws As Worksheet
Set ws = ActiveSheet
For Each cell In ws.Columns(2).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
End Sub
這將遍歷活動工作表中B列的每個單元格,並選擇它遇到的第一個空單元格。 要將工作表設置為特定的一個, Set ws = ActiveSheet
Set ws = Sheets("EnterSheetNameHere")
或者您可以嘗試使用:
Sub test()
Dim ws As Worksheet
Set ws = ActiveSheet
For Each cell In ws.Columns(2).Cells
If Len(cell) = 0 Then cell.Select: Exit For
Next cell
End Sub
我的問題通過使用以下代碼解決。
Sheets("sheet1").Select
Dim LR2 As Long, cell2 As Range, rng2 As Range
With Sheets("sheet1")
LR2 = .Range("B" & Rows.Count).End(xlUp).Row
For Each cell2 In .Range("B8:B" & LR2)
If cell2.Value <> "" Then
If rng2 Is Nothing Then
Set rng2 = cell2
Else
Set rng2 = Union(rng2, cell2)
End If
End If
Next cell2
rng2.Select
End With
只是我的兩分錢。
該函數將查找范圍中第一個遇到的BLANK單元,因此它應適用於列和行。
'Find first BLANK cell in a given range, returnt a range (one cell)
Function FirstBlank(ByVal rWhere As Range) As Range
Dim vCell As Variant
Dim answer As Range
Set answer = Nothing
For Each vCell In rWhere.Cells
If Len(vCell.Formula) = 0 Then
Set answer = vCell
Exit For
End If
Next vCell
Set FirstBlank = answer
End Function
然后對單元格進行任何您想要的操作。
嘗試使用此代碼選擇單元格B10下的第一個空單元格。 但這要求B10和B11被預先占用。
Range(“ B10”)。End(xlDown).Offset(1、0)。選擇
要么
范圍(“ B100000”)。結束(xlUp)。偏移量(1、0)。選擇
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.