【发布时间】:2015-11-20 10:36:49
【问题描述】:
让我的循环正确跳过记录时遇到问题。我有多个记录需要从许多从工作簿中更新。每个奴隶都有一个不同的名称(它的用户),我需要通过只比较那些包含用户名称的记录,然后比较唯一的 ID,而不是它当前所做的,来使我的“更新”循环更有效,这是比较所有唯一 ID 以找到匹配项。
我当前的命令按钮只是在列中查找用户名,如果计数高于 0,它会调用模块来更新该用户的记录。
在 Master 和 Slave 中,第 1 列始终是记录的唯一 ID,第 2 列始终是记录分配给的用户。这是我目前的测试编码(将成为其他用户工作簿的模板):
Option Explicit
Public Sub Agnes_Update()
Dim owb As Workbook
Dim Master, Slave As Worksheet
Dim fpath As String
Dim i, j As Integer
fpath = Application.ActiveWorkbook.Path & "\Agnes.xlsx"
Set owb = Application.Workbooks.Open(fpath)
Set Master = ThisWorkbook.Worksheets("Allocated")
Set Slave = owb.Worksheets("Work")
For j = 2 To 10 '(the master sheet)
For i = 2 To 10 '(the slave sheet)
'if ID cell is blank exit - ends loop when all updates are completed
If Trim(Slave.Cells(j, 1).Value2) = vbNullString Then Exit For
'if column 2 of master does not contain the current username being
'updated then move to next record
If Master.Cells(j, 2).Value = "Agnes" Then
'if unique ID in column 1 matches slave from master then begin
'updating of required cells
If Master.Cells(i, 1).Value2 = Slave.Cells(j, 1).Value2 Then
Master.Cells(i, 4).Value = Slave.Cells(j, 4).Value
Master.Cells(i, 5).Value = Slave.Cells(j, 5).Value
Master.Cells(i, 6).Value = Slave.Cells(j, 6).Value
Master.Cells(i, 7).Value = Slave.Cells(j, 7).Value
Master.Cells(i, 8).Value = Slave.Cells(j, 8).Value
Master.Cells(i, 9).Value = Slave.Cells(j, 9).Value
Master.Cells(i, 10).Value = Slave.Cells(j, 10).Value
Master.Cells(i, 11).Value = Slave.Cells(j, 11).Value
Master.Cells(i, 12).Value = Slave.Cells(j, 12).Value
Master.Cells(i, 13).Value = Slave.Cells(j, 13).Value
Master.Cells(i, 14).Value = Slave.Cells(j, 14).Value
Master.Cells(i, 15).Value = Slave.Cells(j, 15).Value
Master.Cells(i, 16).Value = Slave.Cells(j, 16).Value
Master.Cells(i, 17).Value = Slave.Cells(j, 17).Value
Master.Cells(i, 18).Value = Slave.Cells(j, 18).Value
Master.Cells(i, 19).Value = Slave.Cells(j, 19).Value
Master.Cells(i, 20).Value = Slave.Cells(j, 20).Value
Master.Cells(i, 21).Value = Slave.Cells(j, 21).Value
Master.Cells(i, 22).Value = Slave.Cells(j, 22).Value
Master.Cells(i, 23).Value = Slave.Cells(j, 23).Value
End If
End If
Next
Next
Workbooks("Agnes").Close
End Sub
我更喜欢使用Master.cells = Slave.cells的方法,因为一些从单元格被锁定以防止用户修改数据,并且将来某些数据的位置可能会改变列,所以我将简单地修改哪个主列= 哪个从属列。我意识到我可以设置代码来解锁工作簿,但对于简单的更新来说,这需要更多的代码。
我相信代码的当前问题在于 If Master.Cells(j, 2).Value = "Agnes" Then 行,因为删除此行允许代码通过所有唯一 ID 来查找和更新所有匹配的主控,但我宁愿它只尝试当在第 2 列中找到用户名时匹配唯一 ID,以尝试使代码更快、更高效。
谁能帮我改正这段代码?
【问题讨论】:
-
|这里的错误不是很清楚。即使行中的名称是“Agnes”,子程序是否永远不会进入内部
If?您是否需要从Master.Cells(j, 2).Value中删除前导或尾随空格? -
嗨@stucharo 抱歉,我的问题是分配的工作表永远不会更新从属的
Agnes记录,即使它在单元格中,我也无法这样做。跨度>
标签: excel if-statement for-loop updates vba