Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 从列的单元格复制到特定单元格_Vba_Excel_Cell - Fatal编程技术网

Vba 从列的单元格复制到特定单元格

Vba 从列的单元格复制到特定单元格,vba,excel,cell,Vba,Excel,Cell,我正在为Excel创建代码,以便将上一列中某个单元格的内容复制到下一个单元格。我要复制其内容的单元格为绿色。但我需要搜索整个工作簿和所有工作表中的所有内容,因为每个绿色单元格可以位于不同的列中。我的代码是: Dim wb As Workbook Dim sht As Worksheet frow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row fcol = Cells.Find("*", [A1], , , xlByRows, xlPr

我正在为Excel创建代码,以便将上一列中某个单元格的内容复制到下一个单元格。我要复制其内容的单元格为绿色。但我需要搜索整个工作簿和所有工作表中的所有内容,因为每个绿色单元格可以位于不同的列中。我的代码是:

Dim wb As Workbook
Dim sht As Worksheet
frow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
fcol = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Column
Cells.UnMerge


Set wb = ActiveWorkbook


For Each sht In wb.Sheets
    For ncol = 1 To fcol
        For nrow = 1 To frow
            If Cells(nrow, ncol).Interior.Color = RGB(0, 128, 0) Then

                Cells(nrow, ncol - 1).Copy
                Cells(nrow, ncol).Select
                ActiveSheet.Paste
                Cells(nrow, ncol).Interior.Color = RGB(0, 128, 0)
            End If
        Next
    Next
但问题是,在某些工作表中,带有绿色单元格的列是空的,代码只获取带有内容的所有列(因此fcol是totalColumnstoProcess-1),因此它不会将内容复制到我想要的单元格中

总而言之:我想转到工作簿中的所有工作表,检测哪里有绿色单元格,并将该内容复制到下一列同一行

是否有其他方法处理工作表中的所有内容?
你知道为什么我的代码不起作用吗?

除非我遗漏了什么,否则这不起作用吗

dim r as range
dim ws as worksheet
for each ws in worksheets
  for each r in ws.usedrange
    if r.Interior.Color = RGB(0, 128, 0) Then
        r = r.offset(0,-1)
     end if
  next r
next ws

我认为你的代码可能有一些问题

  • 您需要逐个工作表定义工作表的搜索区域,因此它需要位于循环中
  • UsedRange
    通常是要避免的,因为它既能提取格式又能提取内容,但在您的情况下,它会工作得很好。活动区域定义仅拾取内容
  • 下面的代码应该会有所帮助,但如果有两个相邻的绿色单元格,则需要更多考虑

        Dim ws As Worksheet
        Dim rng As Range
        Dim cell As Range
        Const GREEN As Long = 32768 'RGB(0, 128, 0)
    
        For Each ws In ThisWorkbook.Worksheets
            ' Define the range we want to interrogate
            Set rng = ws.UsedRange
            ' Check we have some cells to work with.
            If rng.Cells.Count > 1 Or rng.Cells(1, 1).Interior.Color = GREEN Then
                For Each cell In rng
                    'Find a green cell, making sure it isn't in Column "A"
                    If cell.Column > 1 And cell.Interior.Color = GREEN Then
                        cell.Value = cell.Offset(, -1).Value2
                        'if you want to delete the old cell's value then uncomment the next line
                        cell.Offset(, -1).Value = vbNullString
                    End If
                Next
            End If
        Next