[英]Excel VBA Column Range selection selecting wrong columns
I'm working on a macro that will run on multiple worksheets in one Workbook, switching between sheets and copying/pasting data to one master sheet. 我正在处理一个宏,该宏将在一个工作簿中的多个工作表上运行,在工作表之间切换并将数据复制/粘贴到一个主表中。
My issue is that when I switch to another sheet using Windows(index).Activate and then try to select some columns to delete, it doesn't select the columns correctly. 我的问题是,当我使用Windows(index).Activate切换到另一张工作表,然后尝试选择要删除的某些列时,它没有正确选择这些列。 I'm using the code below, and the EXACT same code works just fine in the master sheet, but as soon as I switch to another sheet in the VBA code and use it, it selects all columns starting with column 1 to the end of the data.
我正在使用下面的代码,并且完全相同的代码在主表中也可以正常工作,但是一旦我切换到VBA代码中的另一个表并使用它,它将选择从列1到末尾的所有列。数据。
The idea behind the code below is to start at Column 1 and search for the column called "Composite Rating". 下面的代码背后的想法是从第1列开始,然后搜索称为“综合评分”的列。 I then want to DELETE all columns starting at column 3 up to the Composite Rating column.
然后,我想删除从第3列到“综合评分”列的所有列。
Can someone tell me what I'm doing wrong? 有人可以告诉我我在做什么错吗? Thank you very much for any help!
非常感谢您的帮助!
For counter = 1 To 40 Step 1
Cells("1", counter).Select
strval = ActiveCell.Value
If strval = "Composite Rating" And counter <> 3 Then
Range(Cells(1, 3), Cells(1, counter - 1)).EntireColumn.Select
Selection.Delete Shift:=xlLeft
Exit For
End If
Next counter
EDIT: Sorry, should have mentioned my setup. 编辑:对不起,应该提到我的设置。 I am using Excel 2007 on Windows 7. I've tried on both xls and xlsx files, same result.
我在Windows 7上使用Excel2007。我在xls和xlsx文件上都尝试过,结果相同。
Try below code : 试试下面的代码:
Dim rng As Range
Set rng = Range("A1:Z1").Find("Composite Rating")
If Not rng Is Nothing Then
If rng.Column > 3 Then
Range("C1", rng).EntireColumn.Delete
End If
End If
The index
property in the Windows
collection changes when selecting other windows -> it's relative! 选择其他窗口时,
Windows
集合中的index
属性会更改->它是相对的!
Use the Workbooks
collection instead. 请改用
Workbooks
集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.