在上一段代码中,我运行了一个Range.Find方法,以返回在特定列中找到特定日期的所有工作表的名称。 “How do I get vba loop result to populate a combobox?”然后使用这些工作表名称填充组合框(CboReviewModule)。在此子例程中,希望用户从此组合框中选择一个工作表名称。进行选择后,我希望Range.Find方法在所选工作表的第40列中运行,找到保存在变量(myDate)中的日期值的第一次出现,然后将单元格设置为Activecell。之后,我使用.offset填充一系列文本框,其中所有单元格的值都位于Activecell的左侧。
我无法弄清楚如何使Range.Find方法返回正结果。以下代码是许多失败尝试的最新版本:
Private Sub CboReviewModule_Change()
Dim ws As Worksheet
Dim wsName As String
Dim myDate As Date
Dim rngFind As Range
Dim firstAddress As String
Dim iCount As Integer
Dim myArray(38) As Variant
'Set date variable equal to value of combobox selection
myDate = Me.CboReviewWeek.Value
'MsgBox (myDate) '{test successful}
'Set ws name variable equal to value of combobox
wsName = Me.CboReviewModule.Value
'MsgBox (wsName) '{test successful}
With ActiveWorkbook.Worksheets(wsName)
'Run Find command on defined range and save result to range variable
Set rngFind = .Columns(40).Find(What:=myDate, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False).Row
'***** Add line to clear CboReviewModule each time the CboReviewWeek is changed. ***** _
****** Once a module is found on the selected date, the module Cbo won't clear when choosing a new date. *****
'If cell is empty, loop to next row, if cell value matches myDate _
then pass cell address value to string variable
If rngFind Is Nothing Then
GoTo myNext
ElseIf rngFind = myDate Then
Do 'do this thing
'set values of array by cell contents to the left of active cell
myArray(0) = ActiveCell.Offset(, -39).Value
myArray(1) = ActiveCell.Offset(, -38).Value
myArray(2) = ActiveCell.Offset(, -37).Value
myArray(3) = ActiveCell.Offset(, -36).Value
myArray(4) = ActiveCell.Offset(, -35).Value
'and so on
'populate values of userform cells based on contents of array
Me.TxtAccount.Value = myArray(0)
Me.TxtMR.Value = myArray(1)
Me.TxtName.Value = myArray(2)
Me.TxtType.Value = myArray(3)
Me.TxtFinClass.Value = myArray(4)
Loop While rngFind.Address <> firstAddress And Not rngFind Is Nothing
End If
End With
myNext:
Next Cell
答案 0 :(得分:0)
以下是在 40 列中找到特定日期的一种方法:
Sub FindingChristmas()
Dim myDate As Date, r As Range
Dim colmn40 As Range
Set colmn40 = Range("AN:AN")
myDate = DateSerial(2014, 12, 25)
Set r = colmn40.Find(What:=myDate, After:=colmn40(1))
r.Select
End Sub
答案 1 :(得分:0)
找到保存在变量(myDate)中的日期值的第一次出现,然后将单元格设置为Activecell。之后,我使用.offset填充一系列文本框,其中包含位于Activecell左侧的所有单元格的值。
.Find
的代码是正确的。但是,您错误地使用了后面的部分。将ActiveCell
替换为rngFind
试试这个
Set rngFind = .Columns(40).Find(What:=mydate, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlRows, _
SearchDirection:=xlNext, _
MatchCase:=False).Row
If Not rngFind Is Nothing Then
myArray(0) = rngFind.Offset(, -39).Value
'
'~~> Rest of the code
'
End If