2012-10-24 35 views
0

我見過很多人在討論這個問題,但更多的是從將複合單元格複製到單個單元格的角度。我有一個從工作簿獲取範圍的過程,打開第二個工作簿並嘗試將其粘貼到指定行中的下一個空白單元格中;複製範圍搜索連續的下一個空單元格,但跳過合併單元格

Public Sub BankBalances() 
Dim fname As String 
Dim fname2 As String 
Dim mt As String, yr As String 
'get the selected month 
mt = MonthBox.Value 
'get the selected year 
yr = YearBox.Value 
'set the file path to the selected year, month and the saving format 
fname = yr & mt & "DB" & ".xlsx" 
'set the file path to the selected year, month to open the trial balance sheet 
fname2 = yr & mt & "TB" & ".xlsx" 
'get the ranges 
Dim rng1 As Range 
Dim rng2 As Range 
Set rng1 = Workbooks(fname2).Worksheets("excel").Range("I100") 
'check for the next empty cell in row 55 
Set rng2 = Workbooks(fname).Worksheets("UK monthly dashboard").Cells(55, Columns.Count).End(xlToLeft).Offset(0, 1) 
'set the new range to hold the data from the original range 
rng2.Value = rng1.Value 
'set the result to format according to the other information in the workbook 
rng2.Value = Round(rng1.Value/1000, 0) 

End Sub 

上面的代碼會將數據粘貼到未合併行中的下一個空白單元格中。我需要它能夠粘貼到合併的單元格中。

我想知道的是,如果有一種方法使用VBA將數據放入合併的單元格中,或者如果我需要執行單獨的過程來檢查合併的單元格,請取消合併,然後合併數據已經複製過。

如果是這樣,我能否以類似的方式來檢查下一個空單元格,然後檢查它是否合併,然後執行拆分並再次合併。

+0

可能重複? http://stackoverflow.com/questions/13028201/first-empty-cell-in-row – CustomX

+0

它是相似的,但這是一個問題,只是讓範圍複製它不是重複的。其次,這是我的問題,第三,它只是保持開放,以查看是否有人提出任何事情,但我很高興該關閉 – JamesDev

+0

因此,如果你複製細胞A1:A5並且你有D1:D5合併,那麼你想要合併的單元格內的A1:A5「內部」的內容嗎? –

回答

1

如果我明白你在說什麼,那麼是的,但如果我可以改變你的例子,我想把A1的內容放入D1:D2合併。所以它的一個細胞進入兩個值合併在一起 - JamesDev 4小時前

這是你正在嘗試?

Sub Sample() 
    Dim Rng1 As Range 
    Dim Rng2 As Range 
    Dim ws As Worksheet 

    Set ws = ThisWorkbook.Sheets("Sheet1") 

    With ws 
     Set Rng1 = .Range("A1") 
     Set Rng2 = .Range("D1:D2") 

     '~~> Check if cells are merged 
     If Rng2.MergeCells Then 
      '~~> If merged then write to first cell 
      Rng2.Cells(1, 1).Value = Rng1.Value 
     Else 
      Rng2.Value = Rng1.Value 
     End If 
    End With 
End Sub 
+0

這正是我想要的。 ......但它並沒有足夠古怪地解決這個問題,它仍在跳過這些單元格並將其放置在所需目的地的右側。這些單元都有破折號,我以前沒有想過,但是在檢查時意味着它們的值爲0。我試圖刪除它,看看它是否工作,但仍然沒有什麼 – JamesDev

+0

好,所以把所有的格式化和刪除值,然後允許這個工作,所以我會高興地將它標記爲正確的答案。實現查看範圍是否很簡單,以查看是否存在0,刪除它並刪除所有格式,複製範圍並重新應用格式? – JamesDev

相關問題