我有一个带有两个工作表的 Excel 工作簿。
工作表 1 是一个需要填写的表单,它有一个提交按钮(使用 VBA 创建),它获取数据并将其添加到工作表 2 上的下一个空行。
因此,表 2 填充了先前提交的表单信息,并且可以清除表 1(再次通过使用 VBA 创建的按钮),为下一批信息做好准备。
每个条目都有一个唯一编号以供引用,但我想做的是在表 1(表格)上有一个所有唯一编号的下拉列表,我可以选择一个,并为它带来所有相关信息返回表单,以便可以进行任何编辑,并使用一个按钮来保存/覆盖数据,而不是将其另存为新行。
因此希望能够将数据带回工作表 1 以进行编辑/修改/保存/覆盖。
我的 VBA 知识有限,因为这是我处理的第一个项目,所以我仍在学习基础知识。
任何意见或建议将不胜感激。
非常感谢
瑞秋。
最佳答案
我已经整理了一个简单的示例来演示您的要求,可以下载 here .
我做了以下事情:
Private Sub Worksheet_Change(ByVal Target As Range)
'check that the Target cell is our dropdown
If Target.Address = "$C$2" Then
'get the value of the dropdown using the range method
Dim dropDownValue As String
dropDownValue = CStr(wsForm.Range(Target.Address).Value)
'if that dropdown value exists (has a length of more than zero)
If Len(dropDownValue) > 0 Then
'get the corresponding record from the data sheet
Dim index As Integer
index = Left(dropDownValue, 1)
wsForm.Range("C3").Value = index
wsForm.Range("C4").Value = Application.WorksheetFunction.VLookup(index, wsData.Range("A:E"), 2, False)
wsForm.Range("C5").Value = Application.WorksheetFunction.VLookup(index, wsData.Range("A:E"), 3, False)
wsForm.Range("C6").Value = Application.WorksheetFunction.VLookup(index, wsData.Range("A:E"), 4, False)
End If
End If
End Sub
它使用 vlookups 从数据表中检索信息以填充编辑表单。
Sub Button4_Click()
Dim index As Integer
index = wsForm.Range("C3")
If index > 0 Then
Dim foundIndexRange As Range
Set foundIndexRange = wsData.Range("A:A").Find(index)
If (Len(foundIndexRange.Value) > 0) Then
foundIndexRange.Offset(0, 1).Value = wsForm.Range("C4").Value
foundIndexRange.Offset(0, 2).Value = wsForm.Range("C5").Value
foundIndexRange.Offset(0, 3).Value = wsForm.Range("C6").Value
End If
MsgBox "Record saved"
Else
MsgBox "Please choose from the dropdown"
End If
End Sub
它使用 range.Find 方法来定位我们的索引在数据表上的范围,然后偏移以覆盖我们的新值。
我希望这是有道理的,请询问您是否有任何问题。
关于vba - 通过下拉列表将数据从一张表导出到另一张表 - VBA Excel 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42387332/