我想創建一個命令按鈕,它復制一系列單元格并將它們粘貼到下一個空范圍內。
我在網上找到了一個代碼,我對其進行了調整以執行該功能,但是當我添加條件格式時它不起作用。
條件格式為,空白單元格 = 黃色。
我當前使用的 VBA 是:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Set copySheet = Worksheets("Sheet1")
Set pasteSheet = Worksheets("Sheet1")
copySheet.Range("B11:J11").Copy
pasteSheet.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial xlPasteAll
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
如果我在空白單元格中輸入一個值,上面的 VBA 作業正常,但是如果我將單元格留空,它不會粘貼到下一個單元格中。
目的是讓用戶根據需要粘貼盡可能多的行,黃色陰影表示要在哪些單元格中添加值。
我希望這是有道理的。我不是特別習慣excel中的這些功能。
uj5u.com熱心網友回復:
試試這個代碼:
Private Sub CommandButton1_Click()
'Macro to copy in a new row.
'Turning off screen updating.
Application.ScreenUpdating = False
'Declarations.
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim targetRange As Range
'Setting variables.
Set copySheet = Worksheets("Sheet1")
Set pasteSheet = Worksheets("Sheet1")
'Setting targetRange as the last cell in column B with value.
Set targetRange = pasteSheet.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0)
'Setting targetRange as the first cell in column B with no conditional formatting under the last cell in column B with no value.
Do Until targetRange.FormatConditions.Count = 0
Set targetRange = targetRange.Offset(1, 0)
Loop
'Copying range B11:J11.
copySheet.Range("B11:J11").Copy
'Pasting the copied range in targetRange.
targetRange.PasteSpecial xlPasteAll
'Turning off the cut-copy mode.
Application.CutCopyMode = False
'Turning on the screen updating.
Application.ScreenUpdating = True
End Sub
我已經獲取了您的代碼并添加了變數targetRange。然后將所述變數設定為 B 列中具有值的最后一個單元格(類似于您已經完成的操作),然后我使用 Do Loop 回圈設定targetRange為第一個單元格,在 B 列中具有值的最后一個單元格下沒有條件格式. 我還在整個代碼中添加了正確的注釋。
評論中要求的額外代碼。
您可以在使用以下公式將任何“傳出”值計算為 7 時獲得范圍值的總和:
=SUM(B11:B15,COUNTIF(B11:B15,"ongoing")*7)
您可以在宏中使用相同的公式,如下所示:
Sub Macro1()
'A example of macro to return a range sum with any "ongoing" switched with 7.
'Declaration.
Dim rng As Range
'Setting the seed range.
Set rng = Range("B11")
'Expanding rng to the last cell with value of its column.
Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))
'Reporting in the immediate window the result.Debug.Print Excel.WorksheetFunction.Sum(rng, Excel.WorksheetFunction.CountIf(rng, "ongoing") * 7)
Debug.Print Excel.WorksheetFunction.Sum(rng, Excel.WorksheetFunction.CountIf(rng, "ongoing") * 7)
'Reporting in the immediate window the result, this time using a With End With statement to make it more readable.
With Excel.WorksheetFunction
Debug.Print .Sum(rng, .CountIf(rng, "ongoing") * 7)
End With
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492537.html
