[英]VBA Script to Loop Through Specific Date Range
Good evening StackOverflow cohort, 晚上好,StackOverflow队列,
After an interesting baptism by fire in learning VBA, I have a more advanced question regarding executing my script in a loop. 在学习VBA之后,经历了一次有趣的洗礼之后,我有一个关于循环执行脚本的更高级的问题。 Currently, I have the script referencing a cell in a specific worksheet, which houses the current date.
当前,我有一个脚本引用一个特定工作表中的单元格,该工作表中包含当前日期。 The script places this date into a variable portion of a URL string, which then executes data retrieval from this webpage.
该脚本将该日期放置在URL字符串的可变部分中,然后从该网页执行数据检索。
My goal is to include DATEDIF somewhere within this to signify how many days are missing between the last available data pulled and today's date. 我的目标是将DATEDIF包括在其中,以表示从上次获取的可用数据到今天的日期之间缺少多少天。 If possible, the script would then be able to adjust the variable URL string accordingly to replace each date through this loop, then add the data in the sheet below the previous pulled data.
如果可能的话,脚本将能够相应地调整变量URL字符串,以通过此循环替换每个日期,然后将数据添加到工作表中先前提取的数据下方。 This is my script so far below:
到目前为止,这是我的脚本:
Sub MasterDataIngest()
Dim sh1 As Worksheet
Dim wkb As Workbook
With wkb
Set sh1 = Worksheets("SheetOne")
Set wkb = Workbooks("SheetTwo")
Set IE = CreateObject("InternetExplorer.Application")
sh1.Activate
IE.Visible = False
IE.navigate "http://website.com/dir1/dir2/" & Format(Cells(1, 1).Value, "yyyymmdd") & "/file.txt"
'Check for good connection to web page loop!
Do
If IE.readyState = 4 Then
IE.Visible = False
Exit Do
Else
DoEvents
End If
Loop
'Wait for window to open!
Application.wait (Now + TimeValue("0:00:02"))
IE.Visible = False
IE.navigate "http://website.com/dir1/dir2/" & Format(Cells(1, 1).Value, "yyyymmdd") & "/file.txt"
IE.ExecWB 17, 0 '// SelectAll
IE.ExecWB 12, 2 '// Copy selection
sh1.PasteSpecial Format:="Text", link:=False, DisplayAsIcon:=False
sh1.Range("A2").Select
IE.Quit
End With
End Sub 结束子
You can do this easily with DateDiff
. 您可以使用
DateDiff
轻松完成此操作。
If you call DateDiff like this: 如果您这样调用DateDiff:
Sub Test()
Dim a as Long
Dim b as Date
Dim c as Date
b = CDate(Cells(1,1).Value)
c = CDate(Cells(1,2).Value)
a = Abs(DateDiff("d",b,c))
Debug.Print("The difference in days between b and c is " & a)
End Sub
This will give you the number of days between two supplied dates. 这将为您提供两个提供的日期之间的天数。 With this you can easily check how long its been since you last checked if you compare the last date you have with the current date (You can use
Now()
for this) 有了它,您可以轻松地检查自从上次检查以来已经有多长时间了,如果您将最近的日期与当前日期进行比较(可以使用
Now()
进行此操作)
You can read more about how to use the DateDiff
function on that tutorial, too. 您也可以在该教程上阅读有关如何使用
DateDiff
函数的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.