我有一张名为" JE"的表格,在C栏(C7:C446)中,用户可以通过两种方法用帐号代码填充单元格:
acct_codes
#N/A
表中未列出该帐户代码,则会进行检查并更改为acct_codes
向用户表明他们输入的代码不正确。 列E是一个帐户描述列,它将显示与列C中的帐户代码关联的描述。
就像现在一样,下一个可用的单元格是C列中的下一个空白单元格。我想让E列中等于#N/A
的任何单元格成为下一个可用单元格,那么下一个空白单元格可以是下一个可用单元格。
例如如果单元格E11的值为#N/A
,则下次用户导航到acct_codes
工作表并双击有效的帐户代码时,我希望他们点击的帐户代码覆盖并填充C11。
我不确定完成此操作的语法,并且很难在网上找到这个好例子。如果有人知道我可以这样做的方式,我会非常感激。
以下是acct_codes
表中的代码:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim acctDesc As Range
Set acctDesc = Range("E7:E446")
If Target.Column = 1 Then
For j = 7 To 447
If Worksheets("JE").Range("C" & j).Value = "" Then
Worksheets("JE").Range("C" & j).Value = ActiveCell.Value
Worksheets("JE").Activate
Exit For
End If
Next j
End If
For Each Cell In acctDesc
If Cell.Value = "#N/A" Then
'Make that next available cell'
'else make next blank cell next available'
End If
Next Cell
Cancel = True
End Sub
修改
Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim NextAvailableCell As Range
With ThisWorkbook.Sheets("JE")
Set NextAvailableCell = .Range("C7:C447").Find(What:="#N/A", _
LookAt:=xlWhole, _
LookIn:=xlValues)
If NextAvailableCell Is Nothing Then
Set NextAvailableCell = .Range("C7:C448").End(xlUp).Offset(1, 0)
.Cells(NextAvailableCell.Row, "C").Value = Target.Value
End If
End With
NextAvailableCell.Value = Target.Value
Cancel = True
Call Back_to_JE 'calls a macro that brings user back to main form/sheet "JE"
End Sub
答案 0 :(得分:0)
使用Find
Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim NextAvailableCell As Range
With ThisWorkbook.Sheets("JE")
' Set equal to next "#N/A" cell
Set NextAvailableCell = .Range("C7:C447").Find(What:="#N/A", _
LookAt:=xlWhole, _
LookIn:=xlValues)
' If no "#N/A" cell was found then get last empty cell in column,
' assuming it's above C448
If NextAvailableCell Is Nothing Then
Set NextAvailableCell = .Range("C448").End(xlUp).Offset(1, 0)
End If
End With
' Assign value of double clicked cell
NextAvailableCell.Value = Target.Value
' Make it so that the double clicker doesn't enter the cell
Cancel = True
End Sub
这也避免了激活和选择,这是一种很好的做法。
我不确定您要写入哪个单元格。如果您要在#N/A
列而不是列E
中搜索C
,只需在.Range(___).Find
行中进行更改即可。同样在相关行中的下一个空白单元格。
如果您想写到特定列,比如列E
,请使用类似
' Inside the With block for ThisWorkbook.Sheets("JE")
.Cells(NextAvailableCell.Row, "E").Value = Target.Value