使用Combobox通过功能和外部链接填充单元格

时间:2017-03-27 19:34:31

标签: excel excel-vba combobox vba

这很简单,但我无法弄清楚。也许是因为它无法完成?无论如何我们走了:

我想使用一个组合框,当选择它时,输入具有文本值,函数和外部单元格引用的单元格。

选项的第一行是填充名称。

第二行是一个会从课程变为课程的公式。

第三行将为一个单元格提供另一个文件中另一个单元格内容的引用。因此,如果使用多个课程文件,我可以拥有一个主文件,如果我更改单元格的内容,则更改将反映更新后引用它的所有课程文件单元格。

这是粗略的代码形式,我希望它能够执行。

    Private Sub ComboBox1_Change()
If Me.ComboBox1.Value = "ITCourse" Then
    Worksheets("PARADE STATE").Range("I1").Value = "ITCourse"
    Worksheets("Data Base").Range("C1").Value = IF(V9>70,"Prep Week",IF(V9>65,"Week 1",IF(V9>60,"Week 2",IF(V9>55,"Week 3",IF(V9>50,"Week 4",IF(V9>45,"Week 5",IF(V9>40,"Week 6",IF(V9>35,"Week 7",IF(V9>30,"Week 8",IF(V9>25,"Week 9",IF(V9>20,"Week 10",IF(V9>15,"Week 11",IF(V9>10,"Week 12",IF(V9>5,"Week 13",IF(V9>0,"Week 14")))))))))))))))
    Worksheets("Week 1").Range("B2").Value = 'N:\ITcourse\00 - Data Base\[ITcourse.xlsx]Sheet'!$A$3
End If
If Me.ComboBox1.Value = "HRCourse" Then
    Worksheets("PARADE STATE").Range("I1").Value = "HRCourse"
    Worksheets("Data Base").Range("C1").Value = IF(V9>40,"Prep Week",IF(V9>35,"Week 1",IF(V9>30,"Week 2",IF(V9>25,"Week 3",IF(V9>20,"Week 4",IF(V9>15,"Week 5",IF(V9>10,"Week 6",IF(V9>5,"Week 7",IF(V9>5,"Week 8")))))))))
    Worksheets("Week 1").Range("B2").Value = 'N:\ITcourse\00 - Data Base\[HRcourse.xlsx]Sheet'!$A$3
End If
End Sub

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要一个函数来返回任何给定课程名称的周数。此函数应使用Dictionary来存储信息,并且可以从专用工作表加载字典。

Function WeeksPerCourse(courseName As String) As Long
    Static dict As Scripting.Dictionary
    If dict Is Nothing Then
        ' Fill the dictionary here. Note that it is better
        ' to load the values from a dedicated, hidden worksheet
        Set dict = CreateObject("Scripting.Dictionary")
        dict("ITCourse") = 14
        dict("HRCourse") = 8
        ' Etc...
    End If
    WeeksPerCourse = dict(courseName)
End Function

使用此功能,您的程序可以简化如下:

Private Sub ComboBox1_Change()
    Dim course As Sting: course = Trim(ComboBox1.value)
    Worksheets("PARADE STATE").Range("I1").value = course

    'Dim nWeek As Long
    'nWeek = WeeksPerCourse(course) - Worksheets("PARADE STATE").Range("V9").value / 5
    'Worksheets("Data Base").Range("C1").value = IIf(nWeek < 1, "Prep Week", "Week " & nWeek)

    Worksheets("Data Base").Range("C1").Formula = "= ""Week "" & INT((WeeksPerCourse('PARADE STATE'!I1) - 'PARADE STATE'!V9)/5)"

    Worksheets("Week 1").Range("B2").Formula= "='N:\ITcourse\00 - Data Base\[" & course & ".xlsx]Sheet'!$A$3"
End Sub