Excelmacros连接单元格并切换
我希望能够select任意数量的单元格(全部在同一行),然后运行一个将连接所有突出显示的单元格的macros,然后将所有剩余的单元格移过来。
我的描述可能不太清楚 – 希望这样做更有意义:
在下面的例子中,我有第1到第8列中的数据。我将突出显示列1到3中的单元格,运行macros,并将突出显示的单元格中的值合并到左侧(之间有空格),并使剩余的细胞转移。
之前
Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8 ABCDEFGH
后
Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8 ABCDEFGH
这可能与macros(我会通过键盘快捷键执行)做? 我已经对excel和vbamacros有了一个大致的了解,但是我很遗憾地不知道这是否可行。
我发现一些连接单元格数据的macros,但不是基于突出显示的单元格。 任何意见,将不胜感激。 谢谢。
试试这个:
Sub bigmac() Dim r As Range, rDel As Range Set r = Selection Dim N As Long N = r.Count Set rn = r(N) st = "" For i = 1 To N st = st & r(i).Value Next i r(1) = st Set rDel = Range(r(2), r(N)) rDel.Delete shift:=xlToLeft End Sub
这绝对是可能的。 执行取决于你想要如何“Hgihlight”细胞。 如果你select它们,你只需要在你的代码中使用.selection
。
这是我用来组合列的function:
Function combineColumns(ByVal Columns As Variant, ByVal EmptyCol As Long) As String Dim tempColumn As Long Dim str As String Dim base As Long base = LBound(Columns) 'Columns could be 0 or 1 based array str = "=" 'compiles string formula for combining the columns For i = base To UBound(Columns) 'tempColumn = Range(Columns(i) & "1").column If i > base Then 'if i > base it means that the loop is not on the first run, so the "&" is added for concatenation str = str & "&"" ""&RC[-" & (EmptyCol - Columns(i)) & "]" Else str = str & "RC[-" & (EmptyCol - Columns(i)) & "]" End If Next combineColumns = str End Function
该函数接受一个列号数组,并返回一个可插入到单元格中的string,以将传递的列组合到传入的空白列中。 应该很容易适应你的解决scheme。 (循环.selection
列,并将所有列号添加到数组,然后传递给我的函数,并使用返回的string。)
如果使用颜色突出显示,则使用循环遍历行中的每个单元格并testing颜色。 如此
For Each cell In activeCell.entireRow.Cells if cell.interior.color = RGB() then 'insert rgb for highlighting color here 'add to array end if next
然后你会传递结果数组。 然后在合并单元格之后,使用.delete xlShiftToLeft
将删除单元格,并将剩下的行移到左侧以填充空格。 (请确保没有在该点select组合数据的单元格。
编辑
注意:函数返回的string必须插入到一个单元格中( Cells(rownum, colnum).formulaR1C1 =
),因为如果你试图在代码之外使用它,你会得到一个错误