我想這是你在找什麼:
Sub CopyNonBlankCells()
Dim cel As Range, myRange As Range, CopyRange As Range
Set myRange = Sheet1.Range("C1:C20") '---> give your range here
For Each cel In myRange
If Not IsEmpty(cel) Then
If CopyRange Is Nothing Then
Set CopyRange = cel
Else
Set CopyRange = Union(CopyRange, cel)
End If
End If
Next cel
CopyRange.Copy Sheet2.Range("C1") '---> enter desired range to paste copied range without blank cells
End Sub
上面的代碼將在複製範圍到C1
在Sheet2
從here得到這個。
編輯:以下的答案是基於您的評論 ________________________________________________________________________________
如果你會寫類似下面
Set myRange = Sheet1.Range("G:G")
Set myRange = Sheet2.Range("G:G")
myRange
將是第一套Sheet1.Range("G:G")
再到Sheet2.Range("G:G")
這意味着電流範圍myRange
將有Sheet2.Range("G:G")
。
如果您想使用多個範圍,您可以使用UNION
函數,但有一個侷限性,即使用UNION,您可以將不同的範圍組合到一個工作表中。而您的要求是結合不同工作表的範圍。爲了做到這一點,我添加了一個新的工作表,並將所有工作表中的G:G
範圍添加到它中。然後在使用新添加的表格後,我將其刪除。
以下代碼將在名爲Result
的表中爲您提供所需的輸出。
Sub CopyNonBlankCells()
Dim cel As Range, myRange As Range, CopyRange As Range
Dim wsCount As Integer, i As Integer
Dim lastRow As Long, lastRowTemp As Long
Dim tempSheet As Worksheet
wsCount = Worksheets.Count '--->wsCount will give the number of Sheets in your workbook
Set tempSheet = Worksheets.Add '--->new sheet added
tempSheet.Move After:=Worksheets(wsCount + 1)
For i = 1 To wsCount
If Sheets(i).Name <> "Result" Then '---> not considering sheet "Result" for taking data
lastRow = Sheets(i).Cells(Rows.Count, "G").End(xlUp).Row '--->will give last row in sheet
lastRowTemp = tempSheet.Cells(Rows.Count, "G").End(xlUp).Row '--->will give last row in newly added sheet
Sheets(i).Range("G1:G" & lastRow).Copy _
tempSheet.Range("G" & lastRowTemp + 1).End(xlUp)(2)
End If
Next i
lastRowTemp = tempSheet.Cells(Rows.Count, "G").End(xlUp).Row
Set myRange = tempSheet.Range("G1:G" & lastRowTemp) '--->setting range for removing blanks cells
For Each cel In myRange
If Not IsEmpty(cel) Then
If CopyRange Is Nothing Then
Set CopyRange = cel
Else
Set CopyRange = Union(CopyRange, cel)
End If
End If
Next cel
CopyRange.Copy Sheets("Result").Range("G1") '---> enter desired range to paste copied range without blank cells
Application.DisplayAlerts = False
tempSheet.Delete '--->deleting added sheet
Application.DisplayAlerts = True
End Sub
沒有靈丹妙藥這裏。堆棧溢出不是我網站的代碼。此外,您的帖子中還沒有足夠的信息可供我們甚至猜測您想要的內容。我們將幫助解決現有代碼中的特定問題。 –