【问题标题】:Excel Macro to concatenate cells and shift overExcel宏连接单元格并转移
【发布时间】:2014-04-19 18:25:33
【问题描述】:

我希望能够选择任意数量的单元格(都在同一行),并运行一个宏来连接所有突出显示的单元格,然后移动所有剩余的单元格。

我的描述可能不太清楚 - 希望这更有意义:

在下面的示例中,我在第 1 到第 8 列中有数据。 我将突出显示 1 到 3 列中的单元格,运行宏,并将突出显示的单元格中的值合并到左侧(之间有空格),并将剩余的单元格移动。

之前

Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8
A       B       C       D       E       F       G       H

之后

Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8
A B C   D       E       F       G       H

这可能与宏(我通过键盘快捷键执行)有关吗?我对 excel 和 vba 宏有一个大致的了解,但遗憾的是我还不足以知道这是否实用或可能。

我发现了一些连接单元格数据的宏,但不是基于突出显示的单元格。任何意见,将不胜感激。谢谢。

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

    • 保留您的编辑,但将 r(1)=st 替换为 r(1)=Trim(st)
    【解决方案2】:

    这绝对是可能的。执行取决于您希望如何“Hgihlight”单元格。如果您选择它们​​,您只需在代码中使用.selection

    这是我用来合并列的函数:

    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
    

    该函数接受一个列号数组,并返回一个字符串,该字符串可以插入到单元格中以将传递的列组合到传递的空白列中。应该很容易适应您的解决方案。 (遍历.selection 中的列并将所有列号添加到数组中,然后传递给我的函数,并使用返回的字符串。)

    如果您使用颜色突出显示,您将使用循环遍历行中的每个单元格并测试颜色。很喜欢

    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 删除单元格并将剩余的单元格移到左侧以填充空白。 (确保此时没有选择包含组合数据的单元格。

    编辑

    注意:函数返回的字符串必须插入到单元格 (Cells(rownum, colnum).formulaR1C1 =) 中,因为如果您尝试在代码之外使用它,则会收到错误提示

    【讨论】:

      猜你喜欢
      • 2011-04-22
      • 2023-04-05
      • 2018-07-16
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多