我想根据(ctrl +鼠标点击)
之类的值选择范围内的单元格
如果G列的值包含单词 Wage 和 Sum ,则会选中该值。在图片的情况下,将选择 5/15 WAGES SUMMARY 和 4/15 WAGES SUMMARY 。
如果选择的计数仅为1,则将显示其数量(列j)。
如果选择的数量是2或更多,那么将比较日期。在图片的情况下,它是(5/15和4/15)。将比较日期以获得最高。如果有两个或更多最高日期,则会添加金额,如果只有一个,则会显示。这是我的代码;
Dim ws1 As Worksheet, wsm As Worksheet
Dim wb1 As Workbook
Dim Loc As Range
Dim crt As Integer, r As Long, c As Long, last As Long
ctr = 0
i = 3
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("SHIPNET102")
Set wsm = wb1.Sheets("MACRO TEMPLATE")
last = ws1.Cells(Rows.Count, "A").End(xlUp).Row
Do Until ws1.Cells(i, 7) = ""
Set Loc = ws1.Cells(i, 7).Find(What:="*WAGE*SUM*")
If Loc Is Nothing Then
i = i + 1
Else
ctr = ctr + 1
i = i + 1
End If
Loop
If ctr > 1 Then
'?
Else
r = Loc.Row
c = Loc.Column + 3
wsm.Cells(5, 3) = ws1.Cells(r, c)
End If
到目前为止,这是我的结果。它只计算包含单词工资和总和的单元格数量,如果计数仅为1,则显示金额。任何帮助都将不胜感激。
答案 0 :(得分:1)
我为你添加了一些线条。如果它不起作用,请告诉我。
Dim ws1 As Worksheet, wsm As Worksheet
Dim wb1 As Workbook
Dim Loc As Range
Dim crt As Integer, r As Long, c As Long, last As Long
Dim CellsToSelect As String
ctr = 0
i = 3
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("sheet2")
Set wsm = wb1.Sheets("Sheet1")
last = ws1.Cells(Rows.Count, "A").End(xlUp).Row
Do Until ws1.Cells(i, 7) = ""
Set Loc = ws1.Cells(i, 7).Find(What:="*WAGE*")
If Loc Is Nothing Then
i = i + 1
Else
If CellsToSelect = Empty Then
CellsToSelect = ws1.Cells(i, 7).Address
Else
CellsToSelect = CellsToSelect & "," & ws1.Cells(i, 7).Address
End If
ctr = ctr + 1
i = i + 1
End If
Loop
If ctr > 1 Then
ws1.Range(CellsToSelect).Select
Else
r = Loc.Row
c = Loc.Column + 3
wsm.Cells(5, 3) = ws1.Cells(r, c)
End If
使用以下代码比较日期:
Sub Program()
Dim Str As String, str2 As String
Dim MonthS As String, YearS As String
Dim DateS As Date
Str = "12/18 WAGES SUMMARY "
str2 = Trim$(Left$(Str, InStr(Str, " ") - 1))
MonthS = Trim$(Left$(str2, InStr(str2, "/") - 1))
YearS = Trim$(Right$(str2, Len(str2) - InStr(str2, "/")))
DateS = "1/" & MonthS & "/" & YearS
If DateS > "5/8/16" Then
a = 1
Else
a = 2
End If
End Sub
答案 1 :(得分:0)
如果您的列G值可以采用多种格式(" 4/15 WAGE SUMMARY"," WAGE SUMMARY 4/15"等),那么您可能希望考虑使用正则表达式从文本中提取日期。
在VBA中,可以在Microsoft VBScript Regular Expressions库中找到正则表达式,您可以通过转到Tools>从项目中引用它。 VB编辑器中的参考文献。
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
http://www.regular-expressions.info/vb.html
一旦你提取了字符串的日期部分,就可以转换为具有内置CDate函数的日期,并比较两个日期以获得最新日期。
您使用的一般方法的另一个问题是,当您反复使用“查找”时,您不会保存有关先前检查过的单元格的状态,这对于比较已解析的日期是必要的。
我建议创建一个函数(让它调用GetDate(str as String)),它将获取一个字符串参数,如果字符串有" WAGE"和"摘要"和一个可解析的日期,返回日期,否则如果输入字符串不匹配则返回Nothing。
在列H处插入一个填充了公式= GetDate(G2)的列。然后按H列中的日期对数据进行排序。现在,您可以遍历符合条件和总和的行,直到找不到日期,或者日期变旧。