简体   繁体   中英

VBA Macro Error used with VLOOKUP

I recently used code from a post by @LondonRob, which allows the format of a cell to be carried over with the containing data when using VLOOKUP.

Original question - Vlookup to copy color of a cell - Excel VBA

This is great and works for the majority of values. Unfortunately some values can't have the format carried across and I receive the error:

Run-time error "13": Data mismatch

I have taken out all empty cells and by trial and error taken out any formula errors and corrected misspellings. There are still a few cells bring this message up when trying to run the macro.

I can't see any errors in the data, and the occurrence of this error in cells appears to be almost random. The data set is also huge, so even finding all the problematic cells is proving difficult (I have located a few).

I would have commented on the thread, but I don't have the reputation at this point.

The coding used is (though in my module I took out the first 6 lines) -

Option Explicit
' By StackOverflow user LondonRob
' See https://stackoverflow.com/questions/22151426/vlookup-to-copy-color-of-a-cell-excel-vba

Public Sub formatSelectionByLookup()
  ' Select the range you'd like to format then
  ' run this macro
  copyLookupFormatting Selection

End Sub

Private Sub copyLookupFormatting(destRange As Range)
  ' Take each cell in destRange and copy the formatting
  ' from the destination cell (either itself or
  ' the vlookup target if the cell is a vlookup)
  Dim destCell As Range
  Dim srcCell As Range

  For Each destCell In destRange
    Set srcCell = getDestCell(destCell)
    copyFormatting destCell, srcCell
  Next destCell

End Sub

Private Sub copyFormatting(destCell As Range, srcCell As Range)
  ' Copy the formatting of srcCell into destCell
  ' This can be extended to include, e.g. borders
  destCell.Font.Color = srcCell.Font.Color
  destCell.Font.Bold = srcCell.Font.Bold
  destCell.Font.Size = srcCell.Font.Size

  destCell.Interior.Color = srcCell.Interior.Color

End Sub

Private Function getDestCell(fromCell As Range) As Range
  ' If fromCell is a vlookup, return the cell
  ' pointed at by the vlookup. Otherwise return the
  ' cell itself.
  Dim srcColNum As Integer
  Dim srcRowNum As Integer
  Dim srcRange As Range
  Dim srcCol As Range

  srcColNum = extractLookupColNum(fromCell)
  Set srcRange = extractDestRange(fromCell)
  Set srcCol = getNthColumn(srcRange, srcColNum)
  srcRowNum = Application.Match(fromCell.Value, srcCol, 0)
  Set getDestCell = srcRange.Cells(srcRowNum, srcColNum)

End Function

Private Function extractDestRange(fromCell As Range) As Range
  ' Get the destination range of a vlookup in the formulat
  ' of fromCell. Returns fromCell itself if no vlookup is
  ' detected.
  Dim fromFormula As String
  Dim startPos As Integer
  Dim endPos As Integer
  Dim destAddr As String

  fromFormula = fromCell.Formula

  If Left(fromFormula, 9) = "=VLOOKUP(" Then
    startPos = InStr(fromFormula, ",") + 1
    endPos = InStr(startPos, fromFormula, ",")
    destAddr = Trim(Mid(fromFormula, startPos, endPos - startPos))
  Else
    destAddr = fromCell.Address
  End If
  Set extractDestRange = fromCell.Parent.Range(destAddr)

End Function

Private Function extractLookupColNum(fromCell As Range) As Integer
  ' If fromCell contains a vlookup, return the number of the
  ' column requested by the vlookup. Otherwise return 1
  Dim fromFormula As String
  Dim startPos As Integer
  Dim endPos As Integer
  Dim colNumber As String

  fromFormula = fromCell.Formula

  If Left(fromFormula, 9) = "=VLOOKUP(" Then
    startPos = InStr(InStr(fromFormula, ",") + 1, fromFormula, ",") + 1
    endPos = InStr(startPos, fromFormula, ",")
    If endPos < startPos Then
      endPos = InStr(startPos, fromFormula, ")")
    End If
    colNumber = Trim(Mid(fromFormula, startPos, endPos - startPos))
  Else
    colNumber = 1
  End If

  extractLookupColNum = colNumber

End Function

Private Function getNthColumn(fromRange As Range, n As Integer) As Range
  ' Get the Nth column from fromRange
  Dim startCell As Range
  Dim endCell As Range

  Set startCell = fromRange(1).Offset(0, n - 1)
  Set endCell = startCell.End(xlDown)

  Set getNthColumn = Range(startCell, endCell)

End Function

Thanks

There's a lot of code there, so it's difficult to say what the exact issue might be.

Try this version:

Sub tester()
    Dim c As Range
    If TypeName(Selection)<>"Range" Then Exit Sub
    For Each c In Selection
        CopySourceFormats c
    Next c
End Sub


'If the passed cell has a VLOOKUP formula,
'  extract the arguments and find the source of the return value.
'Copy formatting from that cell to the cell with the formula
Sub CopySourceFormats(c As Range)
    Dim arr, v, rng As Range, col As Long, f As String
    Dim m, fs As Font, fd As Font, rngSrc As Range

    'skip any unwanted cells
    f = c.Formula
    If Not f Like "=VLOOKUP(*" Then Exit Sub
    If IsError(c.Value) Then Exit Sub 'no "source" cell to find



    'Extract just the arguments and create an array 
    '  (assumes no arguments contain a comma: 
    '  would need better parsing otherwise)
    f = Replace(f, "=VLOOKUP(", "")
    f = Left(f, Len(f) - 1)
    arr = Split(f, ",")

    v = c.Parent.Evaluate(arr(0)) 'get lookup value
    Set rng = Evaluate(arr(1))    'source table (could be on another sheet)
    col = CLng(arr(2))            'column number in lookup table

    'Debug.Print v, rng.Address(), col

    'Try to match the value in the first column of the lookup table
    m = Application.Match(v, rng.Columns(1), 0)

    'Got a match? Copy formatting for the "source" cell
    If Not IsError(m) Then
        Set rngSrc = rng.Cells(m, col)
        Set fs = rngSrc.Font
        Set fd = c.Font
        'copy formatting: add/subtract properties to suit...
        fd.Size = fs.Size
        fd.Color = fs.Color
        fd.Bold = fs.Bold
        c.Interior.ColorIndex = rngSrc.Interior.ColorIndex
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM