返回列表 上一主題 發帖

請教合併儲存格問題

回復 4# morris0914
  1. Sub Compare()
  2.     Dim R As Integer, C As Integer, TheCoL As Integer
  3.     On Error GoTo Er
  4.     With ActiveWorkbook
  5.         .Sheets.Add(, .Sheets(.Sheets.Count)).Name = "合併"
  6.     End With
  7.     With Sheets("合併")
  8.         .Move Sheets(2)
  9.         Sheets(3).Range("A1").CurrentRegion.Copy .[A1]
  10.         R = .[A1].End(xlDown).Row + 2
  11.         For C = 1 To Sheets(3).UsedRange.Columns.Count
  12.             For i = 3 To Sheets.Count
  13.                  TheCoL = .Cells(R, .Columns.Count).End(xlToLeft).Column + 1
  14.                  If .Cells(R, .Columns.Count).End(xlToLeft) = "" Then TheCoL = 1
  15.                 With Sheets(i)
  16.                     .Range(.Cells(R, C), .Cells(.Rows.Count, C)).Copy Sheets("合併").Cells(R, TheCoL)
  17.                 End With
  18.             Next
  19.         Next
  20.     End With
  21.     Exit Sub
  22. Er:                    '處裡 "合併" 工作表已存在
  23.     Application.DisplayAlerts = False
  24.     ActiveSheet.Delete
  25.     Sheets("合併").Delete
  26.     Application.DisplayAlerts = True
  27.     Resume
  28. End Sub
複製代碼
感恩的心......(在麻辣家族討論區.用心學習會有進步的)
但資源無限,後援有限,  一天1元的贊助,人人有能力.

TOP

回復 7# morris0914
Q:我的頁面是(menu, 合併, 4.log, 5.log)為何是1 To Sheets(3),而不是Sheets(3) to.....
A: Sheets(3).UsedRange.Columns.Count ,解釋: 第3個工作表(4.log).已使用範圍.欗位.物件數目= 4.log已使用範圍的欄數

Q:  為何讀到xlToLeft為空白時,TheCol=1,而不是用xlToright
TheCoL = .Cells(R, .Columns.Count).End(xlToLeft).Column + 1  '資料寫在左邊的欄位 + 1
A: 如此 A欗會空著

Q:為何用到2次Cells   
A:VBA的說明
  1. Application、Range 及 Worksheet 物件時用 Range 屬性。
  2. 傳回 Range 物件,該物件代表一個儲存格或儲存格範圍。
  3. expression.Range(Cell1, Cell2)
複製代碼
感恩的心......(在麻辣家族討論區.用心學習會有進步的)
但資源無限,後援有限,  一天1元的贊助,人人有能力.

TOP

        靜思自在 : 閒人無樂趣,忙人無是非。
返回列表 上一主題