【发布时间】:2017-11-21 11:00:48
【问题描述】:
我有这个 VBA 宏,它在一个范围内搜索“SV”并用某个值(“PEL-SVFC”)更新另一个单元格。我想要扩展它,所以它只在它本身包含另一个值(PEL-CD)的情况下更新该单元格,然后再更改它,但我收到类型不匹配错误。
以下是宏、当前的工作版本以及引发类型不匹配错误的版本:
Sub Update3011()
'Update various values in the 3011
'Define some variables
Dim PromoNameColumn As Range
Dim PromoNameColumnAsArray As Variant
Dim AccountNameColumn As Range
Dim AccountNameColumnAsArray As Variant
Dim i As Long
'First action: search cells in column W for text containing "SV". Of those matches, if the cell in column D of that row matches "PEL-CD", replace it with "PEL-SVFC".
Set PromoNameColumn = Range("W2:W" & ThisWorkbook.Worksheets("3011").UsedRange.Rows.Count)
PromoNameColumnAsArray = PromoNameColumn ' PromoNameColumnAsArray is now array
Set AccountNameColumn = Range("D2:D" & ThisWorkbook.Worksheets("3011").UsedRange.Rows.Count)
AccountNameColumnAsArray = AccountNameColumn ' AccountNameColumnAsArray is now array
For i = LBound(PromoNameColumnAsArray, 1) To UBound(PromoNameColumnAsArray, 1)
If InStr(1, PromoNameColumnAsArray(i, 1), "SV") Then 'If the range "W2:2" contains SV and the range "D2:D" contains "PEL-CD", continue
AccountNameColumnAsArray(i, 1) = "PEL-SVFC"
End If
Next
AccountNameColumn = AccountNameColumnAsArray
MsgBox ("3011 updated.")
End Sub
还有不工作的:
Sub Update3011()
'Update various values in the 3011
'Define some variables
Dim PromoNameColumn As Range
Dim PromoNameColumnAsArray As Variant
Dim AccountNameColumn As Range
Dim AccountNameColumnAsArray As Variant
Dim i As Long
'First action: search cells in column W for text containing "SV". Of those matches, if the cell in column D of that row matches "PEL-CD", replace it with "PEL-SVFC".
Set PromoNameColumn = Range("W2:W" & ThisWorkbook.Worksheets("3011").UsedRange.Rows.Count)
PromoNameColumnAsArray = PromoNameColumn ' PromoNameColumnAsArray is now array
Set AccountNameColumn = Range("D2:D" & ThisWorkbook.Worksheets("3011").UsedRange.Rows.Count)
AccountNameColumnAsArray = AccountNameColumn ' AccountNameColumnAsArray is now array
For i = LBound(PromoNameColumnAsArray, 1) To UBound(PromoNameColumnAsArray, 1)
If InStr(1, PromoNameColumnAsArray(i, 1), "SV") And InStr(1, AccountNameColumnAsArray(i, 1), "PEL-CD") Then 'If the range "W2:2" contains SV and the range "D2:D" contains "PEL-CD", continue
AccountNameColumnAsArray(i, 1) = "PEL-SVFC"
End If
Next
AccountNameColumn = AccountNameColumnAsArray
MsgBox ("3011 updated.")
End Sub
因此,导致错误的位是if 语句中的And InStr(1, AccountNameColumnAsArray(i, 1), "PEL-CD"),这是代码块之间唯一不同的地方。
如何在更新单元格之前修改此代码以添加额外的逻辑检查?
【问题讨论】: