2013-02-28 50 views
0

我有一個宏,旨在檢查字符串「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

您遇到看起來是與線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 
+0

完美 - 謝謝! – user2108977 2013-02-28 20:50:48

+0

@ user2108977標記爲正確? – Lopsided 2013-02-28 21:20:32

+0

是的。我怎麼做? – user2108977 2013-03-01 02:32:30

相關問題