我试图找出一个VBA,以根据单元格中的值选择同一行中的单元格范围。 示例:假设A1单元格的单元格值为“ 5”,那么它将选择5个相邻的单元格(B1:F1),然后为这5个单元格输入“ OK” 然后,VBA将继续在病房中检查A2的n值是否与上述相同,但是如果它在A列中找到第一个空白单元格,则VBA将停止
答案 0 :(得分:0)
以下内容将检查列A上有数据的最后一行,然后将检查每一行以确认列A中所保存的值是数字,然后在列之间循环多次,并用“确定”填充单元格“:
Sub ColumnALoop()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
For i = 1 To LastRow
'loop through Rows
If IsNumeric(ws.Cells(i, 1).Value) Then ws.Range("B" & i).Resize(, ws.Cells(i, 1).Value).Value = "OK"
'verify the value in Column A is numeric then enter OK in relevant cells
Next i
End Sub
包括一个工作表更改事件:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:A")) Is Nothing Then
'check if any changes have happened on Column A
For Each c In Target
If c.Column = 1 Then
'ensure that we are looking at Column A as Target could include variable size ranges
If IsNumeric(c) And c.Value <> "" Then Range("B" & c.Row).Resize(, c.Value).Value = "OK"
'if value is numeric and not blank then enter "OK"
End If
Next c
End If
End Sub