【发布时间】:2019-02-17 05:53:25
【问题描述】:
此代码从工作表复制数据并将数据粘贴到 test.csv 文件中。如果 test.csv 已关闭,则将其打开并粘贴 数据放入其中。如果它已经打开,那么只需将数据粘贴到其中。到这一步为止,过程运行良好。数据粘贴后 进入 test.csv,我需要删除第一列值为“旧”的行。然后删除整个 Col "A"。
这是我面临的挑战。如果 test.csv 已关闭,宏将打开它,粘贴数据,然后删除行和列,并按预期工作 ,但是,如果 test.csv 已经打开,那么它会按预期粘贴值,但会删除行和 col 它在 主工作表。我尝试将删除代码放在 With 块中,但没有帮助。请推荐!
Sub Macro()
Dim LR As Long, PR As Long, X As Long, MyCopyRange, MyPasteRange
Dim wb, myData As Workbook, shtPaste As Worksheet
Set wb = ThisWorkbook
'open target csv file if not already opened
If CheckFileIsOpen("test.csv") = False Then
Set myData = Workbooks.Open(strFinalizedForBulkImport & "test.csv")
Else
Set myData = Workbooks("test.csv")
End If
Set shtPaste = myData.Sheets("test")
shtPaste.UsedRange.Clear
With wb.Sheets("Report Grp")
LR = .Range("A" & .Rows.Count).End(xlUp).Row
MyCopyRange = Array("A4:A" & LR, "B4:B" & LR, "C4:C" & LR, "D4:D" & LR) 'Put ranges in an array
MyPasteRange = Array("A1", "B1", "C1", "D1")
If LR > 1 Then
j = 0
For X = LBound(MyCopyRange) To UBound(MyCopyRange) 'Loop the array copying and pasting based on element in the array
.Range(MyCopyRange(j)).Copy
shtPaste.Range(MyPasteRange(j)).PasteSpecial xlPasteValuesAndNumberFormats
j = j + 1
Next
Else
Range("A1") = "No Data Found"
End If
End With
'Problem here, when trying to delete row with "Old" in Col "A" and finally Col "A" delete -
With wb.Sheets("test")
For LR = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
If Range("A" & LR).Value = "Old" Then
Rows(LR).EntireRow.Delete
End If
Next LR
Columns("A").Delete Shift:=xlShiftToLeft
End With
End Sub
【问题讨论】:
-
如果 wb.sheets("test") 不是活动工作表,则需要用句点限定
.Columns("A").Delete Shift:=xlShiftToLeft -
BTW wb 作为变体变暗,现在是工作簿。应该是
Dim wb as workbook, myData As Workbook
标签: excel vba delete-row