繁体   English   中英

单元格中的值更改时,将数据插入同一行

[英]Insert data in same row when a value in a cell is changed

我有从SQL和VFP检索信息并在除A1之外的“ A”列的每个单元格中填充一个下拉列表的代码-这是一个标头。

我需要在用户从“ A”列的下拉列表中选择值的行上填充“ G”列。

我相信我需要在Private Sub Worksheet_SelectionChange(ByVal Target As Range)中的Private Sub Worksheet_SelectionChange(ByVal Target As Range)中。

下面是我想要做的事情。

If cell "a2".valuechanged then
    Set "g2" = "8000"
End if
If cell "a3".valueChanged then
    Set "g3" = "8000"
End if

上面的代码不起作用,但是我认为它很容易理解。 我想使它动态化,所以我没有太多的代码行。

我已经解释了使用Worksheet_Change HERE时需要注意的事件和其他事项

您需要使用与Worksheet_Change Intersect来检查用户对哪个单元格进行了更改。

这是您要尝试的吗?

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    '~~> Check if user has selected more than one cell
    If Target.Cells.CountLarge > 1 Then Exit Sub

    Application.EnableEvents = False

    '~~> Check if the user made any changes in Col A
    If Not Intersect(Target, Columns(1)) Is Nothing Then
        '~~> Ensure it is not in row 1
        If Target.Row > 1 Then
            '~~> Write to relevant cell in Col G
            Range("G" & Target.Row).Value = 8000
        End If
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

尝试这个

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Row > 1 And Target.Column <> 7 Then
    Cells(Target.Row, "G").Value = 8000
  End If
End Sub

如果只需要它在A列上触发,则

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Row > 1 And Target.Column = 1 Then
    Cells(Target.Row, "G").Value = 8000
  End If
End Sub

您不能将if语句放在G列中吗?

如果(A1 <>“”,8000,0)

像这样的其他明智的选择将使您前进:

Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Column = 1 Then
If Target.Value2 <> "" Then
Target.Offset(0, 6) = "8000"
Else
Target.Offset(0, 6) = ""
End If
End If
On Error GoTo 0
End Sub

谢谢罗斯

我有一个类似的问题。 我使用了Siddharth Rout的代码。 我的修改允许用户在a列中粘贴一系列单元格(例如A3:A6),并修改了多个单元格(例如H3:H6)。

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa

'~~> Check if user has selected more than one cell
If Target.Cells.CountLarge < 1 Then Exit Sub
If Target.Cells.CountLarge > 500 Then Exit Sub


Debug.Print CStr(Target.Cells.CountLarge)

Application.EnableEvents = False

Dim the_row As Range
Dim the_range As Range

Set the_range = Target

'~~> Check if the user made any changes in Col A
If Not Intersect(the_range, Columns(1)) Is Nothing Then
    For Each the_row In the_range.Rows
        '~~> Ensure it is not in row 2
        If the_row.Row > 2 Then
            '~~> Write to relevant cell in Col H
            Range("H" & the_row.Row).Value = Now
        End If
    Next
End If

Letscontinue:Application.EnableEvents = True退出子项信息:MsgBox Err.Description简历Letscontinue End子项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM