使用VBA基于VLOOKUP更改文件名

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

我正在尝试将工作表另存为 pdf,并使用 vlookup 使用工作表名称和区域来命名 pdf。我的 vlookup 不起作用,我无法在网上找到答案。如有任何帮助,我们将不胜感激。

Sub ConvertSheetToPDFVlookup()
Dim ws As Worksheet
Dim pdfFileName As String
Dim savePath As String
Dim previousMonth As String
Dim sheetName As String
Dim lookupValue As String
Dim lookupResult As String

' Get the name of the previous month
previousMonth = Format(DateAdd("m", -1, Now), "mmm" & "-" & "yy")

' Create a new folder based on the previous month
savePath = "My desired location" & previousMonth & "\"

' Reference the active sheet
Set ws = ActiveSheet

' Get the sheet name
sheetName = ws.Name

' Perform the VLOOKUP
lookupValue = sheetName
lookupResult = Application.VLookup(lookupValue, Sheets("ContractCode").Range("A1:B132"), 2, False)

' Generate PDF file name based on the sheet name and VLOOKUP result
pdfFileName = savePath & sheetName & " - " & lookupResult & ".pdf"

' Export the active sheet as PDF
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfFileName, Quality:=xlQualityStandard

' Highlight the active sheet tab in green
ws.Tab.Color = RGB(144, 238, 144) ' Light Green

' Optional: Display a message when the process is complete
MsgBox "PDF conversion complete!" & vbCrLf & "PDF saved in: " & pdfFileName, vbInformation
End Sub
excel vba vlookup
1个回答
0
投票

sheetName 是一个无用的变量,所以我将删除它。

要解决您的问题,您可以这样做:

lookupResult = Application.WorksheetFunction.VLookup(lookupValue, Sheets("ContractCode").Range("A1:B132"), 2, False)

或者自行搜索表格:

Dim i as Long
Dim endRow as Long: endRow = 132
For i=1 to endRow
   If Cells(i,1).value = lookupValue Then
      lookupResult = cells(i,2).value
      goto BREAK
   End If
Next i
BREAK:
© www.soinside.com 2019 - 2024. All rights reserved.