我在文件夹中有一个“工作簿A”文件。每两周发送一次更新的版本给我。我想从另一个工作簿“工作簿B”打开此工作簿,同时删除“工作簿A”中的空白行。使用excel激活工作表VBA
打开和删除操作将通过使用宏来进行。
这是我迄今为止的代码。
Sub RemoveEmptyRows()
' this macro will remove all rows that contain no data
' ive named 2 variables of data type string
Dim file_name As String
Dim sheet_name As String
file_name = "C:\Users\Desktop\Workstation_A\Workbook_A.xlsm"
'Change to whatever file i want
sheet_name = "Worksheet_A" 'Change to whatever sheet i want
' variables "i" and "LastRow" are needed for the for loop
Dim i As Long
Dim LastRow As Long
' we set wb as a new work book since we have to open it
Dim wb As New Workbook
' To open and activate workbook
' it opens and activates the workbook_A and activates the worksheet_A
Set wb = Application.Workbooks.Open(file_name)
wb.Sheets(sheet_name).Activate
' (xlCellTypeLastCell).Row is used to find the last cell of the last row
' i have also turned off screen updating
LastRow = wb.ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Application.ScreenUpdating = False
' here i am using a step
' the step is negative
' therefore i start from the last row and go to the 1st in steps of 1
For i = LastRow To 1 Step -1
' Count A - Counts the number of cells that are not empty and the
' values within the list of arguments (wb..ActiveSheet.Rows(i))
' Afterwards deleting the rows that are totally blank
If WorksheetFunction.CountA(wb.ActiveSheet.Rows(i)) = 0 Then
wb.ActiveSheet.Rows(i).EntireRow.Delete
End If
Next i
' used to update screen
Application.ScreenUpdating = True
End Sub
工作片名称包含Worksheet_A
作为其名称后跟一个日期的一部分。例如Worksheet_A 11-2-15
。
在我的代码,我已经赋值的变量sheet_name
到Worksheet_A
sheet_name = "Worksheet_A"
进一步压低我用
.Sheets(sheet_name).Activate
激活工作表。我觉得有下面一行的一个问题:
sheet_name = "Worksheet_A"
因为sheet_name
是不完全Worksheet_A它只包含Worksheet_A作为其名称的一部分。
这是造成problem.The工作簿中打开,但不会出现空白行的删除。
此外还会显示一条错误消息。
运行时错误9:下标超出范围。
如何修改我的代码以便工作表被激活并执行宏操作?
是的,我只有一张工作表 – tania 2015-02-23 05:33:37
非常感谢你 它完美地工作 这真的很有帮助 谢谢你花时间给我启发。这非常有教育意义。 – tania 2015-02-23 05:53:07