VBA Sub,返回一个值

我很抱歉,如果这听起来像一个非常愚蠢的问题,但我是新的使用Excel和VBA,花更多的时间与其他语言。 我发现我正在编写代码更加健壮,我一直在写相同的代码块来一遍又一遍地做同样的事情。 有没有一种方法可以调用这段代码,并获得我正在查找的值,并将其存储为我想要的variables,然后将其用于不同的子元素中。

希望这个例子会使它更清楚。 我想从A1开始search第1行的所有值,直到出现空白值。 我想find值为“Frequency”的单元格,然后返回列索引号。

Sub findFrequency() 'find "Frequency" colum and save the column index number Dim fFreq As String Dim FreqCol As Variant Range("A1").Select fFreq = "Frequency" Do Until IsEmpty(ActiveCell) If ActiveCell.Value = fFreq Then FreqCol = ActiveCell.Column Exit Do End If ActiveCell.Offset(0, 1).Select Loop End Sub 

现在理想情况下,我可以写一个不同的,并使用上述代码中的值

 Sub Execute() Call findFrequency Cells(5, FreqCol).Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent5 .TintAndShade = 0.599993896298105 .PatternTintAndShade = 0 End With End Sub 

我运行这个时出现错误,因为FreqCol的值没有设置为运行Call findFrequency行的任何值。 有没有更好的方法来做到这一点,或者我应该有不同的结构?

尝试这个:

 Function findFrequency() 'find "Frequency" colum and save the column index number Dim fFreq As String Dim FreqCol As Variant Range("A1").Select fFreq = "Frequency" Do Until IsEmpty(ActiveCell) If ActiveCell.Value = fFreq Then findFrequency = ActiveCell.Column Exit Do End If ActiveCell.Offset(0, 1).Select Loop End Function Sub Execute() Dim FreqCol As Long FreqCol = findFrequency() Cells(5, FreqCol).Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent5 .TintAndShade = 0.599993896298105 .PatternTintAndShade = 0 End With End Sub 

为什么循环或select一个单元格来find一个值? 只需使用.Find

 Function findFrequency() As Long Dim ws As Worksheet Dim aCell As Range Set ws = ActiveSheet With ws Set aCell = .Columns(1).Find(What:="Frequency", LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not aCell Is Nothing Then findFrequency = aCell.Column End With End Function 

另外如果没有find“频率”会发生什么。 你也需要迎合。

 Sub Execute() Dim FreqCol As Long FreqCol = findFrequency If FreqCol = 0 Then MsgBox "Frequency not found" Exit Sub End If With Cells(5, FreqCol).Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent5 .TintAndShade = 0.599993896298105 .PatternTintAndShade = 0 End With End Sub 

代码将是这样的。

Main Main子部分是findFrequency,subprocedure是Sub Execute(rng As Range)

 Sub findFrequency() 'find "Frequency" colum and save the column index number Dim fFreq As String Dim FreqCol As Variant Range("A1").Select fFreq = "Frequency" Do Until IsEmpty(ActiveCell) If ActiveCell.Value = fFreq Then FreqCol = ActiveCell.Column Execute Cells(5, FreqCol) Exit Do End If ActiveCell.Offset(0, 1).Select Loop End Sub Sub Execute(rng As Range) With rng.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent5 .TintAndShade = 0.599993896298105 .PatternTintAndShade = 0 End With End Sub