我有一个宏,用于检查字符串“Doc1”和“Doc2”是否出现在第一行(标题)的连续列中。
然后,对于所有后续行,宏应该将Doc1列中的信息与Doc2列中的信息连接起来,并用逗号分隔响应。然后它应该删除整个Doc2列
使用我的代码,这适用于Doc1和Doc2的第一个实例并排。对于其余的,它只是删除Doc2列而不将信息连接到Doc1框。任何有关这方面的帮助将不胜感激。
以下是代码:
Sub test()
Dim CurrCol As Integer
Dim NewValue As String
Dim CurrRow As Integer
CurrCol = 1
RowNum = 1
'set last cell
While Cells(1, CurrCol).Address <> "$HOK$1"
'MsgBox Cells(1, CurrCol).Address & " " & Cells(1, CurrCol).Value
If InStr(Cells(1, CurrCol).Value, "Doc1") > 0 Then
' look at next cell
If InStr(Cells(1, CurrCol + 1).Value, "Doc2") > 0 Then
For i = RowNum + 1 To 10
If Trim(Cells(RowNum + 1, CurrCol + 1).Value) <> "" Then
NewValue = Cells(RowNum + 1, CurrCol).Value & ", " & Cells(RowNum + 1, CurrCol + 1).Value
' MsgBox "New Value is " & NewValue
Cells(RowNum + 1, CurrCol).Value = NewValue
RowNum = RowNum + 1
End If
Next
End If
'now delete currCol+1
Range(Columns(CurrCol + 1), Columns(CurrCol + 1)).Select
Selection.Delete Shift:=xlToLeft
End If
'Advance the counter
CurrCol = CurrCol + 1
Wend
End Sub
答案 0 :(得分:0)
您遇到的问题似乎与行RowNum = RowNum + 1
有关。此行是不必要的,并且导致您的RowNum变量在第一列之后关闭。而是使用i变量来引用您当前所在的行。如果您只想从第2行循环到10(这似乎就是这种情况),您需要进行以下调整:
改变这个:
If InStr(Cells(1, CurrCol + 1).Value, "Doc2") > 0 Then
For i = RowNum + 1 To 10
If Trim(Cells(RowNum + 1, CurrCol + 1).Value) <> "" Then
NewValue = Cells(RowNum + 1, CurrCol).Value & ", " & Cells(RowNum + 1, CurrCol + 1).Value
' MsgBox "New Value is " & NewValue
Cells(RowNum + 1, CurrCol).Value = NewValue
RowNum = RowNum + 1
End If
Next
End If
对此:
If InStr(Cells(1, CurrCol + 1).Value, "Doc2") > 0 Then
For i = 2 To 10
If Trim(Cells(i, CurrCol + 1).Value) <> "" Then
NewValue = Cells(i, CurrCol).Value & ", " & Cells(i, CurrCol + 1).Value
' MsgBox "New Value is " & NewValue
Cells(i, CurrCol).Value = NewValue
End If
Next i
End If