2017-07-07 93 views
0

所以我有一列通過不同模塊列出,一些重複5行,一些20。我試圖通過VBA合併這些,但是我的代碼有些問題。這裏是我使用這個,我已經評論了錯誤發生後,我逐行調試它。希望對此錯誤有任何意見!VBA EXCEL在一列中合併行

謝謝你們!

注:

  • 我開始在7,因爲這是在模塊記錄從開始的行。

    Sub ReMergeECURowsMPNT() 
    
    Dim wsMPNT As Worksheet 
    Set wsMPNT = Worksheets("Module Part Number Tracker") 
    
    Dim lrowMPNT As Long 
    lrowMPNT = CRC.LastRowInMPNT 
    
    Dim i As Long 
    Dim j As Long 
    
    Dim sameRows As Boolean 
    sameRows = True 
    
    For i = 7 To lrowMPNT 
        If StrComp(Cells(i, 3), Cells(i + 1, 3), vbTextCompare) Then 
    
         sameRows = False 
    
        End If 
    
        If sameRows = False Then 
         With wsMPNT 
          .Range(Cells(i, 3), Cells(i + 1, 3)).Merge  '''Application defined error on this line 
         End With 
        End If 
    
        sameRows = True 
    Next i 
    

    末次

+3

嘗試用點出線'Cells':'.Range(.Cells(I,3) .Cells(i + 1,3))。合併' –

+1

另外,我會考慮是否真的需要合併單元格。只是說,因爲在合併單元格中,如果您稍後嘗試在其上運行任何類型的數學/分析/ vba,它可能會有點棘手。見[本頁](http://www.excel-user.com/2012/01/avoid-merged-cells-in-excel.html)或[this one](https://accessanalytic.com.au/停止合併單元格/)爲什麼有些例子。 – BruceWayne

回答

0

除非DisplayAlerts設置爲False,你通常應該得到像提示「選擇包含多個數據值。合併到一個單元格將保留左上角最僅數據「。,如果點擊「取消」而不是「Ok」,VBA將拋出「應用程序定義或對象定義的錯誤」

此外,檢查行lrowMPNT = CRC.LastRowInMPNT。如果您正在尋找合併「列C」,您可以嘗試這樣簡單的東西:

Sub ReMergeECURowsMPNT() 
    Application.DisplayAlerts = False 
    Dim wsMPNT As Worksheet, lrowMPNT As Long, i As Long, j As Long 
    Set wsMPNT = Worksheets("Module Part Number Tracker") 
    wsMPNT.Select 
    lrowMPNT = wsMPNT.UsedRange.Row - 1 + wsMPNT.UsedRange.Rows.Count 
    For i = 7 To lrowMPNT 
     If Cells(i, 3) = Cells(i + 1, 3) Then 
      j = j + 1 
     ElseIf j > 0 Then 
      Range(Cells(i - j, 3), Cells(i, 3)).Merge 
      j = 0 
     End If 
    Next i 
    Application.DisplayAlerts = True 
End Sub