VBA从一年中的周数开始获取开始日期

时间:2018-01-05 10:32:24

标签: excel excel-vba excel-formula vba

我想知道一周的第一天(星期一开始的星期)的日期,知道年份和星期数。 (1年52周)

Dim nYear As Integer, _
    nWeek, As Integer
    startDate As Date

    nYear = 2018
    nWeek= 1


'startDate = ?

预期结果:01/01/2018

有一个简单的&动态的方式呢?

谢谢

3 个答案:

答案 0 :(得分:2)

Dim nTrimester As Integer, _
    nYear As Integer, _
    nWeek As Integer, _
    wd As Integer, _
    startDate As Date, _
    inputDate As Date

nYear = 2019
nWeek = 1    

inputDate = DateSerial(nYear, 1, 1)
inputDate = DateAdd("ww", nWeek - 1, inputDate)
wd = Weekday(inputDate, vbMonday)   

startDate = DateAdd("d", 1 - wd, inputDate)

答案 1 :(得分:0)

我找到了解决方案:

startDate = DateAdd("ww", nWeek, DateSerial(Year(Date), 1, 1))

感谢所有想要帮助的人!

如果您的某些内容相同或更好,请随意添加

答案 2 :(得分:0)

尝试此操作,您必须考虑一年中第一天的星期几。

public class XML_Parser {

public static void main(String[] args)  {

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse("D:\\test.xml");

        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//appSettings/add[@key]");
        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

        for (int c = 0; c < nl.getLength(); c++) {
            Node currentItem = nl.item(c);
            if (currentItem.getAttributes().getNamedItem("key").getNodeValue().equalsIgnoreCase("Date")) {
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Date date = new Date();
                currentItem.getAttributes().getNamedItem("value").setNodeValue(dateFormat.format(date));

            }

        }

        doc.getDocumentElement().normalize();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("D:\\test.xml"));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(source, result);
        System.out.println("XML file updated successfully");

    } catch (Exception e) {
        e.printStackTrace();
    }

}