在下面的vba代码中,如何在excel 2016中通过表格将参数化的“ 09-Oct-18”和文件名设置为_.xlsx。
column A date; column B filename
09-Oct-18 CATEGORY_99_TAS_09-10-2018.xlsx
15-Oct-18 CATEGORY_99_TAS_15-10-2018.xlsx
代码:
If Format(Range("A" & i).Value, "d-mmm-yy") = "09-Oct-18" Then
Range("B" & i).Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(R2C1,'D:\test\files\[CATEGORY_99_TAS_09-10-2018.xlsx]Sheet1'!R2C1:R30C2,2,FALSE)"
Else
If Format(Range("A" & i).Value, "d-mmm-yy") = "15-Oct-18" Then
Range("B" & i).Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(R2C1,'D:\test\files\[CATEGORY_99_TAS_15-10-2018.xlsx]Sheet1'!R2C1:R30C2,2,FALSE)"
答案 0 :(得分:0)
我不知道这部分应该做什么...所以我想您想检查一下A列中的日期是否与b列中工作表名称中的日期匹配:
If Format(Range("A" & i).Value, "d-mmm-yy") = Format(CDate("18-Oct-15"), "d-mmm-yy") Then
根据您的评论,我认为这可能有效。如果您在A列中有一个日期,然后在B列中有一个工作表名称,则宏代码将查看A列中的日期是否等于工作表名称中的日期。如果它们相等,它将打印您可以在B2中看到的公式。否则它将跳到下一行。
Sub Macro1()
Dim FileNameVal As String
Dim FileNameDate As String
Dim YearVal As Integer
Dim MonthVal As Integer
Dim DayVal As Integer
Dim DateCorrect As Date
For i = 2 To 10 'Start loop from row 2 to 10, where every step is row (i)
On Error GoTo Handler 'If cell is empty, then go to Handler:
FileNameVal = Range(Cells(i, "B"), Cells(i, "B")).Value 'Take value in Column B and row i.
If FileNameVal = "" Then 'If cell is empty then go to Handler2:
On Error GoTo HandlerPart2
Else
FileNameDate = Split((Split(Range(Cells(i, "B"), Cells(i, "B")).Value, ".xlsx")(0)), "CATEGORY_99_TAS_")(1) 'Split out the date in the filename
YearVal = Right(FileNameDate, 4) 'Find Year
MonthVal = Mid(FileNameDate, 4, 2) 'Find Month
DayVal = Left(FileNameDate, 2) 'Find Day
DateCorrect = DateSerial(YearVal, MonthVal, DayVal) 'Rearrange date from dd/mm/yyy -> yyyy/mm/dd
If Format(Range("A" & i).Value, "d-mmm-yy") = Format(CDate(DateCorrect), "d-mmm-yy") Then 'Compare the date in column A with the date in column b (date in sheet name), if they are equal then
Range("B" & i).Select 'Select column B and row (i), (this will overwrite the sheet name, I would suggest to use column D)
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(R2C1,'D:\test\files\[" & FileNameVal & "]Sheet1'!R2C1:R30C2,2,FALSE)" ' Print out vlookup formula based on the sheetname.
Else
Handler:
HandlerPart2:
'Do Nothing
End If
End If
Next i
End Sub