VBA MATCH 函数仅在要匹配的值被硬编码时才起作用

问题描述 投票:0回答:1

我无法让下面的 VBA MATCH 函数工作。我需要 VBA 从参考表中获取周数(VBA 成功完成),在搜索表的列中搜索该周数,然后将列号返回到参考表。只有硬编码周数(例如“42”),我才能使 MATCH 函数正常工作。

预先感谢您的帮助。

我一直在尝试工作的代码如下:

Sub Example()
    
    WeekNumber = Worksheets("Reference sheet").Range("E1")
    
    TargetColumn = Application.Match(WeekNumber, ActiveWorkbook.Sheets("Search sheet").Range("3:3"), 0)
    
    Worksheets("Reference sheet").Range("H9").Value = TargetColumn
    
End Sub

我还在 TargetColumn 行中尝试了以下操作:

TargetColumn = Application.Match(Worksheets("Reference sheet").Range("E1").Value, ActiveWorkbook.Sheets("Search shheet").Range("3:3"), 0)

“WeekNumber”是 42。如果我尝试以下操作,该函数将完美运行(它返回列号 46):

TargetColumn = Application.Match("42", ActiveWorkbook.Sheets("Search sheet").Range("3:3"), 0)

如何在不对匹配值进行硬编码的情况下使其工作?预先感谢您的帮助。

excel vba match
1个回答
0
投票

使用
Application.Match

快速修复

Sub Example()
    With ActiveWorkbook
        WeekString = CStr(.Sheets("Reference sheet").Range("E1").Value)
        TargetColumn = Application.Match(WeekNumber, .Sheets("Search sheet").Rows(3), 0)
        .Sheets("Reference sheet").Range("H9").Value = TargetColumn
    End With
End Sub

一步一步(推荐)

Option Explicit

Sub PopulateHeaderColumn()
    
    ' Reference the workbook.
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    ' If it's not, reference the workbook by name or use 'ActiveWorkbook'.
    
    ' Reference the source objects.
    Dim sws As Worksheet: Set sws = wb.Sheets("Search sheet")
    Dim slrg As Range: Set slrg = sws.Rows(3) ' lookup
    ' Contains the week numbers as text.
    
    ' Reference the destination objects.
    Dim dws As Worksheet: Set dws = wb.Sheets("Reference sheet")
    Dim dlcell As Range: Set dlcell = dws.Range("E1") ' lookup
    Dim drcell As Range: Set drcell = dws.Range("H9") ' return
    
    ' Store the week number (converted to a string) in a string variable.
    Dim dlWeek As String: dlWeek = CStr(dlcell.Value)
    ' If the week number from 1 to 9 have a leading 0,
    ' use 'dlWeek = Format(CStr(dlcell.Value),"00")'.
    
    ' Attempt to retrieve the destination column, the left-most column
    ' containing the week (as string).
    Dim drColumn As Variant: drColumn = Application.Match(dlWeek, slrg, 0)
    
    ' If the week is not found, display a message box and exit.
    If IsError(drColumn) Then
        MsgBox "Week " & dlWeek & " was not found in the range ""'" _
            & sws.Name & "'!" & slrg.Address(0, 0) & """!", vbExclamation
        Exit Sub
    End If
    
    ' If the week is found, write it to the destination return cell.
    drcell.Value = drColumn
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.