简体   繁体   English

使用VBA在Excel工作表中动态选择单元格

[英]Dynamically selecting cells in Excel Worksheet using VBA

I'm creating a calendar of months. 我正在创建一个月历。 The user can select a year for the month they want. 用户可以为他们想要的月份选择年份。 When a user selects to create a month, I want to select all the weekdays in that month and give it a named range. 当用户选择创建一个月时,我想选择该月中的所有工作日并为其指定一个命名范围。 How can I select a range of cells for a selected month and year and give it a named range? 如何为选定的月份和年份选择单元格范围,并为其指定命名范围?

Here is the recorded macro (for Jan 2016), but I'm not sure how to create this programmatically. 这是录制的宏(2016年1月),但是我不确定如何以编程方式创建此宏。 I cannot reuse it because what if the user picks a different month or year, then I won't know which row columns contain weekdays. 我无法重复使用它,因为如果用户选择了不同的月份或年份,那我将不知道哪个行列包含工作日。

range( _
    "C9:D9,E9:F9,G9:H9,I9:J9,K9:L9,C11:D11,E11:F11,G11:H11,I11:J11,K11:L11,C13:D13,E13:F13,G13:H13,I13:J13,K13:L13,C15:D15,E15:F15,G15:H15,I15:J15,K15:L15,C17:D17,E17:F17" _
    ).Select
range("E17").Activate
ActiveWorkbook.Names.Add Name:="Test", RefersToR1C1:= _
    "=PTO!R9C3,PTO!R9C5,PTO!R9C7,PTO!R9C9,PTO!R9C11,PTO!R11C3,PTO!R11C5,PTO!R11C7,PTO!R11C9,PTO!R11C11,PTO!R13C3,PTO!R13C5,PTO!R13C7,PTO!R13C9,PTO!R13C11,PTO!R15C3,PTO!R15C5,PTO!R15C7,PTO!R15C9,PTO!R15C11,PTO!R17C3,PTO!R17C5"

----My Code Example---- ----我的代码示例----

For x = 1 to 42
    ' Determine where the 1st day falls
    ' Is it a weekday? Add my coordinates to an array so I can create a named range later.
Next x

CreateNamedRange(weekdayArray)

在此处输入图片说明

If you want to assign selected range into variable Test , you can use following command: 如果要将选定范围分配给变量Test ,可以使用以下命令:

ActiveWorkbook.Names.Add Name:="Test", RefersTo:="=" & ActiveSheet.Name & "!" & Selection.Address

It is impossible for us to help you with selecting some particular cells based on another cell is selcted, without further information about structure of your workbook. 如果没有关于工作簿结构的更多信息,我们将无法帮助您选择基于另一个单元格的某些特定单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM