excel - 如何向此代码添加验证检查?
问题描述
我有此代码来检查 ID 号,然后将 ID 所在的行复制到另一个电子表格中。如果在用户表单中输入的 ID 号不存在,我希望有一条错误消息提示您重试,并且还会取消在输入的 ID 号存在时执行的所有代码
我尝试了一个简单的 If 语句,但没有让它工作
Option Explicit
Private Sub CommandButton1_Click()
Dim wsSource As Worksheet
Set wsSource = Sheets("Arkiv")
Dim wsDestination As Worksheet
Set wsDestination = Sheets("DN")
Dim IDnum As String
IDnum = TextBox1.Text
Dim idRow As Long
idRow = wsSource.Columns("A:A").Find(what:=IDnum, lookat:=xlWhole).Row
Dim SourceAdresses() As Variant
SourceAdresses = Array("B" & idRow, "C" & idRow, "D" & idRow, "E" & idRow, "F" & idRow, "G" & idRow, "H" & idRow, "I" & idRow)
Dim DestinationAdresses() As Variant
DestinationAdresses = Array("D9", "E9", "I9", "C20", "D20", "E45", "g20", "H20", "I20")
Dim i As Long
For i = LBound(SourceAdresses) To UBound(SourceAdresses)
wsDestination.Range(DestinationAdresses(i)).Value = wsSource.Range(SourceAdresses(i)).Value
Next i
wsDestination.Activate
Unload Me
MsgBox "Data is now available"
End Sub
我希望用户表单提示“错误,未找到 ID/存档中不存在”消息并取消所有以下代码的执行,然后让您重试输入 ID
解决方案
我不确定你的整个过程,但下面的代码(未经测试)应该能够让你知道你需要做什么来创建这个错误处理。实际上,使用For
循环会做到这一点......
Option Explicit
Private Sub CommandButton1_Click()
Dim wsSource As Worksheet
Set wsSource = Sheets("Arkiv")
Dim wsDestination As Worksheet
Set wsDestination = Sheets("DN")
Dim IDnum As String
Dim idRow As Long
Dim SourceAdresses() As Variant
Dim DestinationAdresses() As Variant
Dim i As Long, j As Long
For j = 1 To 5
IDnum = TextBox1.Text
idRow = wsSource.Columns("A:A").Find(what:=IDnum, lookat:=xlWhole).Row
If idRow = 0 Then
MsgBox "Error finding ID number! Please try again!"
Else
Exit For
End If
If j = 5 Then
'number of attempts exceeded - end program
MsgBox "Could not locate the ID number! Closing program.."
Exit Sub
End If
Next j
SourceAdresses = Array("B" & idRow, "C" & idRow, "D" & idRow, "E" & idRow, "F" & idRow, "G" & idRow, "H" & idRow, "I" & idRow)
DestinationAdresses = Array("D9", "E9", "I9", "C20", "D20", "E45", "G20", "H20", "I20")
For i = LBound(SourceAdresses) To UBound(SourceAdresses)
wsDestination.Range(DestinationAdresses(i)).Value = wsSource.Range(SourceAdresses(i)).Value
Next i
wsDestination.Activate
Unload Me
MsgBox "Data is now available"
End Sub
推荐阅读
- lda - 如何获得两个模型的主题连贯性分数,然后将其用于比较?
- mysql - 如果 MySQL 数据库中不存在另一个对象,如何创建 SQL 查询来保存对象?
- nuxt.js - 在根路由 NuxtJS 中使用 get param
- php - 如何在php中添加.docx的下载链接
- ios - 本地化自然格式的 API 数据列表
- c++ - 使用选项 -fstack-usage 和 -fdump-rtl-expand 匹配 g++ 生成的文件中的标识符
- azure-active-directory - 有没有办法指定除用户之外的电子邮件以使用 AAD 单点登录 Dropbox?
- angular - 如果路径包含多个斜杠/更改语言中断,则在 Angular 本地化路由器中
- django - django 抛出错误:无效的列名 'id' (SQL SERVER)
- android - Android Rest 身份验证不返回状态代码或网络响应