我的代码当前使用最后一列(在本例中为o列)搜索该列中的所有行,并清除整行,该行在该行的列o中具有特定值。我可以获得一些帮助来修改我的代码以自动选择最后一列,而不是使用该列的字母“o”或值“15”,对于其他电子表格,它可能并不总是使用列o。请参阅下面的工作代码:
Sub edit_wb_1()
Dim wb As Workbook
Dim ws As Worksheet
Dim lastRow As Long, i As Long
Dim value As String
Dim OldDate, NewDate As String
OldDate = Format(DateSerial(Year(Date), Month(Date) - 1, 0), "ddmmyy")
NewDate = Format(DateSerial(Year(Date), Month(Date), 0), "ddmmyy")
Set wb = Workbooks.Open("C:\Users\ashah\Downloads\HistoricSummary.xls", 0)
Set ws = wb.Sheets("Historic Summary Page 1")
lastRow = ws.Range("o" & ws.Rows.Count).End(xlUp).Row
For i = lastRow To 2 Step -1
value = ws.Cells(i, 15).value ' Column O value.
' Check if it contains one of the keywords.
If (value Like "-") Then
ws.Rows(i).ClearContents
End If
Next
wb.SaveAs Filename:="C:\Users\ashah\Documents\TPS Shapes\TMB " & NewDate, FileFormat:=xlOpenXMLWorkbook
wb.Close
End Sub
答案 0 :(得分:0)
Sub edit_wb_1()
Dim wb As Workbook
Dim ws As Worksheet
Dim lastRow As Long, i As Long
Dim lastColumn as Long
Dim value As String
Dim OldDate, NewDate As String
OldDate = Format(DateSerial(Year(Date), Month(Date) - 1, 0), "ddmmyy")
NewDate = Format(DateSerial(Year(Date), Month(Date), 0), "ddmmyy")
Set wb = Workbooks.Open("C:\Users\ashah\Downloads\HistoricSummary.xls", 0)
Set ws = wb.Sheets("Historic Summary Page 1")
lastRow = ws.Range("o" & ws.Rows.Count).End(xlUp).Row
lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column ' gets last column in the first row (where you usually have headers so should be populated...
For i = lastRow To 2 Step -1
value = ws.Cells(i, lastColumn).value ' last col instead of Column O value.
' Check if it contains one of the keywords.
If (value Like "-") Then
ws.Rows(i).ClearContents
End If
Next
wb.SaveAs Filename:="C:\Users\ashah\Documents\TPS Shapes\TMB " & NewDate, FileFormat:=xlOpenXMLWorkbook
wb.Close
End Sub
答案 1 :(得分:0)
以下对代码的更改应该有效。
我假设第1行是标题行。
我还将变量名称value
更改为StrValue
,因为内置的Excel VBA函数使用了value
,这可能会导致歧义。
Sub edit_wb_1()
Dim wb As Workbook
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim Strvalue As String
Dim OldDate As String
Dim NewDate As String
OldDate = Format(DateSerial(Year(Date), Month(Date) - 1, 0), "ddmmyy")
NewDate = Format(DateSerial(Year(Date), Month(Date), 0), "ddmmyy")
Set wb = Workbooks.Open("C:\Users\ashah\Downloads\HistoricSummary.xls", 0)
Set ws = wb.Sheets("Historic Summary Page 1")
'This assumes row one is a header row
i = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
lastRow = ws.Cells(ws.Rows.Count, i).End(xlUp).Row
For i = lastRow To 2 Step -1
Strvalue = ws.Cells(i, 15).value ' Column O value.
' Check if it contains one of the keywords.
If (Strvalue Like "-") Then
ws.Rows(i).ClearContents
End If
Next
Set ws = Nothing
wb.SaveAs Filename:="C:\Users\ashah\Documents\TPS Shapes\TMB " & NewDate, FileFormat:=xlOpenXMLWorkbook
wb.Close 0
Set wb = Nothing
End Sub