如何正确将单元格引用到变量?

时间:2019-09-12 14:22:54

标签: excel vba

我正在尝试在一个变化的位置中打开一个Excel电子表格。变量是日期和文件名:

C:\ Reports \ 2019 \ 09。 2019年9月\ 2019年9月10日\ 1。客户报告\ Report_20190911.csv

我尝试使用变量,并参考工作簿中的特定单元格来添加每天,每月和每年变化的日期。

示例:

Today - C:\Reports\2019\09. September 2019\10 September 2019\1. Client reports\Report_20190911.csv

Tomorrow - C:\Reports\2019\09. September 2019\11 September 2019\1. Client reports\Report_20190912.csv

我似乎无法添加引用的excel单元格的图像,因此我将对其进行描述(所有单元格均由公式驱动以得出日期):

Cell B4 - 10/09/2019 
Cell B6 - 2019
Cell B7 - 09. September 2019
Cell B9 - 10 September 2019

下面是我当前的代码:

Sub Client_Reports()

Dim year_ As Integer
year_ = Cells(6, 2)

Dim month_ As String
month_ = Cells(7, 2)

Dim date_ As Date
date_ = Cells(9, 2)

Dim FilePath As String
Dim FileName As String

FileName = "Report_" & Format(Range("B4") + 1, "yyyymmdd") & ".csv"

FilePath = "C:\Reports\year_\month_\date_\1. Client reports\FileName"

Workbooks.Open (FilePath)

End Sub

运行上述命令时,它将搜索 C:\ Reports \ year_ \ month_ \ date_ \ 1。客户报告\ Report_20190911.csv

请有人可以帮助我解决此问题吗?

谢谢

2 个答案:

答案 0 :(得分:0)

这就是我要做的:

Option Explicit
Sub Client_Reports()

    Dim MyDate As Date
    MyDate = ThisWorkbook.Sheets("MySheet").Range("B4") 'change MySheet to the sheet name holding the date

    Dim MonthName As String
    MonthName = Format(MyDate, "mmmm") 'this takes the month name

    Dim MonthNumber As String
    MonthNumber = Format(MyDate, "mm") 'this takes the month number with 2 digits

    Dim DayNumber As String
    DayNumber = Format(MyDate, "dd") 'this takes the day number with 2 digits, switch to "d" for 1 digit.

    Dim FilePath  As String
    FilePath = "C:\Reports\" & Year(MyDate) & "\" & MonthNumber & ". " & MonthName & "\" & DayNumber & " " & MonthName & _
        " " & Year(MyDate) & "\1. Client reports\"

    Dim FileName
    FileName = "Report_" & Format(MyDate, "yyyymmdd") & ".csv"

    Dim wb As Workbook

    Set wb = Workbooks.Open(FilePath & FileName)

End Sub

这样,您只需要单元格 B4 即可完成其他所有工作。

答案 1 :(得分:0)

如评论中所述,您应该编写以下内容:

FilePath = "C:\Reports\" & year_ & "\" & month_ & "\" & date_ & "\1. Client reports\" & FileName

要构建字符串表达式时,切勿将变量名称放在双引号中。就像将其名称键入为字符串一样,您未引用实际的变量。