2012-04-07 91 views
0

我怎麼可以將選定細胞中的細胞合併到一個細胞中,選定的細胞數量會有所不同,它可能是5個細胞或更多,但所有細胞都會像A1,A2,A3等一樣繼續。 我已閱讀文章 Combine multiple cells into one in excel with macro? 但我怎麼可以使用上面提到的鏈接答案爲選定的單元格。我使用Excel 2007,所以我期望它是可壓縮的代碼。如何在Excel VBA中用逗號合併選定的單元格到一個單元格中?

回答

0

我認爲這應該做的伎倆。它基本上使用範圍變量來處理選擇。然後它使用所選單元格的值填充數組。 CSV是可變的,包含您的結果。

請注意,selectedCells是一個變量,在這裏不是Excel中的一些特殊功能。

[這段代碼在Excel 2002中的工作 - 不確定其他版本]

Dim selectedCells As Range 
Dim rng As Range 
Dim i As Integer 
Dim values() As String 
Dim CSV As String 

' you may need some error handling here in case your selection 
' isn't a range 
Set selectedCells = Selection 

ReDim values(selectedCells.Count - 1) 

i = 0 
For Each rng In selectedCells 
    ' you may want some error handling here when populating the array 
    values(i) = CStr(rng.Value) 
    i = i + 1 
Next rng 

CSV = Join(values, ",") 
+0

提示:這是明智的聲明'我是Long'在更高版本的Excel;) – 2012-04-08 08:09:48

相關問題